Last active
January 28, 2016 07:08
-
-
Save pcanterini/7127d825b3358195b55e to your computer and use it in GitHub Desktop.
Composition over Inheritance in JS
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
// Prototypal OO with ES6 | |
// Eric Elliott's example | |
let animal = { | |
animalType: 'animal', | |
describe () { | |
return `An ${this.animalType}, with ${this.furColor} fur, | |
${this.legs} legs, and a ${this.tail} tail.`; | |
} | |
}; | |
let mouse = Object.assign(Object.create(animal), { | |
animalType: 'mouse', | |
furColor: 'brown', | |
legs: 4, | |
tail: 'long, skinny' | |
}); | |
console.log(mouse.describe()); | |
// better example with Factories | |
let animal = { | |
animalType: 'animal', | |
describe () { | |
return `An ${this.animalType} with ${this.furColor} fur, | |
${this.legs} legs, and a ${this.tail} tail.`; | |
} | |
}; | |
let mouseFactory = function mouseFactory () { | |
let secret = 'secret agent'; | |
return Object.assign(Object.create(animal), { | |
animalType: 'mouse', | |
furColor: 'brown', | |
legs: 4, | |
tail: 'long, skinny', | |
profession () { | |
return secret; | |
} | |
}); | |
}; | |
let james = mouseFactory(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment