Skip to main content

Command Palette

Search for a command to run...

What is mixin in JavaScript?

Published
2 min read
What is mixin in JavaScript?
R

19, Hustler.

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📘

M
Matthew5y ago

Great content for those who want to start web development! It actually has become the dream of this new generation, to be able to make money from home, comfy and easy. On mintme.com you can find interesting information of how digital coins can help you to buy and to earn from home with cryptocurrencies or even with your custom digital coin

C

Hey Rahul,

I think you are missing the actual eventMixin from the first two examples.

That code will result in a error stating eventMixin is not defined.

R
Rahul5y ago

Isn't declaring easy and the reader should do it itself.

(Well have real visitors hehe )

1

More from this blog

R

RAHULISM - FrontEnd Web Developer

232 posts

18, Hustler.