什么是 Mixin 模式?
在 OOP 中,Mixin 是一个类。包含其他类的方法,并且不是通过继承的方式来实现的。
我一般理解成“混合”,在 js 中,其实就是
Object.assign(obj1, obj2)
,将 obj2 原型上的方法引用复制到 obj1 的原型的同名方法中。策略模式优缺点
避免了继承,方法的扩展是松耦合的,支持多个对象的方法进行“混合”。
代码实现
// Mixin模式 // JavaScript是基于原型链,无法多继承 // mixin模式优于其他模式,因为它可以选择性的包括其他类的方法,并且不一定是父类 function Say() {} Say.prototype.hi = function () { console.log("say hi", this.name); }; Say.prototype.hello = function () { console.log("say hello", this.name); }; class User { constructor(name = "") { this.name = name; } bye() { console.log("say bye", this.name); } } /****** 简单的mixins实现 ****/ /** * @param {Object} target * @param {...Object} source */ function mixins(target, ...source) { Object.assign(target, ...source); } /**************************/ // 测试代码 mixins(User.prototype, Say.prototype); const user = new User("hello"); user.hi(); // say hi hello