Hint
Copy methods from multiple sources into a class β avoids single-inheritance limits
A mixin is a pattern to copy methods from one object into another class or prototype, enabling code reuse without inheritance chains.
// Mixin objects (plain objects with methods)
const Serializable = {
serialize() { return JSON.stringify(this); },
};
const Validatable = {
validate() {
return Object.values(this).every(v => v !== null && v !== undefined);
}
};
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
// Apply mixins β copy methods onto the class prototype
Object.assign(User.prototype, Serializable, Validatable);
const u = new User('Alice', 'a@b.com');
u.serialize(); // '{"name":"Alice","email":"a@b.com"}'
u.validate(); // true
// More modern approach: mixin factory functions
const withLogging = (Base) => class extends Base {
log(msg) { console.log(`[${this.constructor.name}] ${msg}`); }
};
class LoggableUser extends withLogging(User) {}
Mixins solve the diamond problem of multiple inheritance β compose behavior from multiple independent sources.