Mixins
A Mixin is a class containing methods that can be used by other classes without inheriting from it. In JavaScript, mixins provide a way to share behavior between classes, overcoming the limitation of single inheritance (a class can only extend one other class).
1. The Problem: Single Inheritance
JavaScript classes support single inheritance.
class User extends Person {
// User inherits from Person
}
If you want User to also have functionality from a Disposable class or an Activatable class, you can't write class User extends Person, Disposable.
2. The Solution: Mixins
A mixin is essentially a function that takes a class as input and returns a new class that extends the input class, adding new methods.
Defining a Mixin
// A Mixin that adds a "sayHi" method
let SayHiMixin = Base => class extends Base {
sayHi() {
console.log(`Hello, ${this.name}!`);
}
};
// A Mixin that adds a "sayBye" method
let SayByeMixin = Base => class extends Base {
sayBye() {
console.log(`Bye, ${this.name}!`);
}
};
Using Mixins
class User {
constructor(name) {
this.name = name;
}
}
// Create a new class that extends User and applies the mixins
class TalkativeUser extends SayHiMixin(SayByeMixin(User)) {}
const user = new TalkativeUser("Alice");
user.sayHi(); // "Hello, Alice!"
user.sayBye(); // "Bye, Alice!"
3. When to use Mixins?
- Shared Behavior: When multiple unrelated classes need to share the same functionality (e.g.,
EventEmitter,Serializable). - Avoiding Deep Hierarchies: Instead of creating a deep inheritance tree (
Animal->Mammal->FlyingMammal->Bat), you can compose behaviors (BatextendsAnimalwithFlyingMixin).
programming/javascript/vanilla/javascript programming/javascript/vanilla/prototypes-and-inheritance programming/javascript/vanilla/es6-features