Computer >> Computer tutorials >  >> Programming >> Javascript

Mixins in JavaScript


JavaScript doesn't support multiple inheritence. But sometimes there is a need to add functionality of 2 classes to a single object. Mixin is a way properties are added to objects without using inheritance.

For example, let's say we have a Person class. And we want people to be able to say Hi. We can create a sayHiMixin and use it to make People say hi −

Example

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 inheritence involved here. We're just copying properties from one object to another. The person class can also inherit from another class while using this mixin.