Composition
- Composition can be used for code reuse
- Favor composition over inheritance.
- With composition, instead of having the complex hierarchy, you can compose a few objects together to create a new object. and this technique gives you great flexibility.
const walkable = {
walk: function() {
console.log("walking");
}
}
const eatable = {
eat: function() {
console.log("eating");
}
}
const swimmable = {
swim: function() {
console.log("swimming");
}
}
Using with simple objects
const person = Object.assign({}, walkable, eatable);
Using with Prototype
function Person() {}
Object.assign(Person.prototype, walkable, eatable);
Using with mixin
// using mixin
function mixin(target, ...sources) {
Object.assign(target, ...sources);
}
mixin(Person.prototype, walkable, eatable);