Javascript-Mixins
JavaScript doesn’t support multiple inheritances. But sometimes there is a need to add the functionality of two classes to a single object. javascript – Mixin is a way properties/methods are added to objects without using inheritance.
Example: Let’s say we have a Person class. And we want people to be able to say Hi. We can generate a say HiMixin and use it to make People say hi −
let sayHiMixin = {
sayHi() {
console.log(`Hello ${this.name}`);
},
sayBye() {
console.log(`Bye ${this.name}`);
}
};
class Person {
constructor(name) {
this.name = name;
}
}
// copy the methods
Object.assign(Person.prototype, sayHiMixin);
new Person("John").sayHi();
OUTPUT:
Hello John
There is no inheritance involved here. We’re just copying properties from one object to another object. The person class can also inherit from another class while using this(keyword) mixin.