A mixin
is an object-oriented programming term, a class which contains helper methods for other classes. Mixin is a JavaScript object with useful methods, which can be easily merged with the prototype of any class.
Usage: In JavaScript, a class can extend only one other class. JavaScript doesn't support multiple inheritances. But sometimes we require to extend more than one, to overcome this we can use Mixin
which helps to copy methods to the prototype of another class.
Example:
class Menu {
choose(value) {
this.trigger("select", value);
}
}
//copy the methods
Object.assign(Menu.prototype, eventMixin);
let menu = new Menu();
menu.addEvent("select", value =>
console.log(`Value selected: ${value}`));
menu.choose("123");
// Value selected: 123
We have used the eventMixin objects addEvent
and trigger
methods to trigger the event using menu object.
eventMixin
Now let's make a Mixin for real-time usage
class Menu {
choose(value) {
this.trigger("select", value);
}
}
//copy the methods
Object.assign(Menu.prototype, eventMixin);
let menu = new Menu();
menu.addEvent("select", value =>
console.log(`Value selected: ${value}`));
menu.choose("123");
// Value selected: 123
We have used the eventMixin objects addEvent
and trigger
methods to trigger the event using menu object.
// Area Calculating Mixin
let areaCalculator = {
calculatorArea() {
console.log(this.length * this.breadth);
}
};
// Usage:
class Rectangle {
constructor(length, breadth) {
this.length = length;
this.breadth = breadth;
}
}
// copy the methods
Object.assign(Rectangle.prototype, areaCalculator);
// now Rectangle class can use calculatorArea
new Rectangle(5, 6).calculatorArea(); // 30
😎Thanks For Reading | Happy Coding📘
%%[bmc]
Top comments (3)
Very useful tricks
Short and Concise. Thanks for the sharing!
Thanks Man.