Mixins
https://javascript.info/mixins (opens in a new tab)
Mixin – is a generic object-oriented programming term: a class that contains methods for other classes.
Using mixin by augmenting existing class behavior,
let sayMixin = {
say(phrase) {
alert(phrase);
}
};
let sayHiMixin = {
__proto__: sayMixin, // (or we could use Object.setPrototypeOf to set the prototype here)
sayHi() {
// call parent method
super.say(`Hello ${this.name}`); // (*)
},
sayBye() {
super.say(`Bye ${this.name}`); // (*)
}
};
class User {
constructor(name) {
this.name = name;
}
}
// copy the methods
Object.assign(User.prototype, sayHiMixin);
// now User can say hi
new User("Dude").sayHi(); // Hello Dude!Limitations
- methods overrides / name clashes
- implicit dependencies
- React suggests composition over mixin for code reuse https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html (opens in a new tab)