Created
December 10, 2016 18:57
-
-
Save KinoAR/e3a1606285df5ff30d05ff4ae60e3668 to your computer and use it in GitHub Desktop.
A gist showcasing object composition, using Object.Assign
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//============================================================================= | |
// Object.Assign | |
//============================================================================= | |
class Robot { | |
constructor(name) { | |
this._name = name; | |
} | |
speak() { | |
console.log(`I am the robot ${this._name}.`); | |
} | |
} | |
class Dog { | |
constructor(name) { | |
this._name = name; | |
} | |
bark() { | |
console.log(`${this._name}: Bowowow`); | |
} | |
} | |
class RobotDog { | |
constructor(name, dog, robot) { | |
//We pass a dog and a robot into the new robot dog to use the methods attach to those instances. | |
Object.assign(this, {dog: dog}, {robot: robot}); | |
this._name = name; | |
console.log(this); //RobotDog {dog: Dog, robot: Robot, _name: "CarlBen"} | |
} | |
bark() { | |
this.dog.bark(); | |
} | |
speak() { | |
this.robot.speak(); | |
} | |
} | |
var robot = new Robot('Carl'); | |
robot.speak();// I am the robot Carl. | |
var dog = new Dog("Ben"); | |
dog.bark(); // Ben: Bowowow | |
var roboDog = new RobotDog('CarlBen', dog, robot); | |
roboDog.bark(); // Ben: Bowowow | |
roboDog.speak(); // I am a robot Carl. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment