Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Created December 10, 2016 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KinoAR/e3a1606285df5ff30d05ff4ae60e3668 to your computer and use it in GitHub Desktop.
Save KinoAR/e3a1606285df5ff30d05ff4ae60e3668 to your computer and use it in GitHub Desktop.
A gist showcasing object composition, using Object.Assign
//=============================================================================
// 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