Mixin 是一种在 JavaScript 中实现代码复用的模式,它允许对象或类从多个源"混入"属性和方法,而不需要使用传统的继承链。
Mixin 是一个包含可复用功能的普通对象,可以被"混入"到其他对象或类中。它不是传统的继承,而是一种组合方式。
const sayMixin = {
sayHi() {
console.log(`Hello ${this.name}`);
},
sayBye() {
console.log(`Bye ${this.name}`);
}
};
class User {
constructor(name) {
this.name = name;
}
}
// 将 mixin 的方法拷贝到 User.prototype
Object.assign(User.prototype, sayMixin);
const user = new User("John");
user.sayHi(); // Hello John
// Mixin 函数
function sayMixin(target) {
target.prototype.sayHi = function() {
console.log(`Hello ${this.name}`);
};
target.prototype.sayBye = function() {
console.log(`Bye ${this.name}`);
};
}
class User {
constructor(name) {
this.name = name;
}
}
// 应用 mixin
sayMixin(User);
const user = new User("John");
user.sayHi(); // Hello John
const sayMixin = Base => class extends Base {
sayHi() {
console.log(`Hello ${this.name}`);
}
sayBye() {
console.log(`Bye ${this.name}`);
}
};
class User {
constructor(name) {
this.name = name;
}
}
// 应用 mixin
class EnhancedUser extends sayMixin(User) {}
const user = new EnhancedUser("John");
user.sayHi(); // Hello John
// 日志功能 Mixin
const loggerMixin = {
log(message) {
console.log(`[${this.name}] ${message}`);
}
};
// 持久化功能 Mixin
const persistenceMixin = {
save() {
console.log(`Saving ${this.name} to database...`);
// 实际保存逻辑
}
};
class Product {
constructor(name) {
this.name = name;
}
}
// 应用多个 mixin
Object.assign(Product.prototype, loggerMixin, persistenceMixin);
const product = new Product("Laptop");
product.log("Created"); // [Laptop] Created
product.save(); // Saving Laptop to database...
Mixin 模式在 JavaScript 库和框架中广泛使用,如 React 之前的高阶组件(HOC)概念就与 Mixin 类似。