FrontendDeveloper.in

JavaScript question detail

Mixin Example using Object composition

// Define a mixin
const canEat = {
eat() {
console.log("Eating...");
}
};

const canWalk = {
walk() {
console.log("Walking...");
}
};

const canRead = {
read() {
console.log("Reading...");
}
};

// Create a class
class Person {
constructor(name) {
this.name = name;
}
}

// Apply mixins
Object.assign(Person.prototype, canEat, canWalk, canRead);

// Use it
const person = new Person("Sudheer");
person.eat();  // Output: Eating...
person.walk(); // Output: Walking...
person.read(); // Output: Reading...
Back to all JavaScript questions
Get LinkedIn Premium at Rs 399