DEV Community

loading...
Cover image for What is mixin in JavaScript?

What is mixin in JavaScript?

rahxuls profile image Rahul ・1 min read

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

😎Thanks For Reading | Happy Coding📘

%%[bmc]

Discussion (3)

pic
Editor guide
Collapse
ravigithub profile image
Ravi Kasireddy

Very useful tricks

Collapse
shwetabh1 profile image
Shwetabh Shekhar

Short and Concise. Thanks for the sharing!

Collapse
rahxuls profile image
Rahul Author

Thanks Man.