JS寄生组合式继承的实现
/** * 对传入的对象进行一次浅复制 * (将被传入的对象复制给这个构造函数的原型) */ function object(o) { function F() {} F.prototype = o; return new F(); } /** * 继承父类圆形,然后返回新对象赋值给子类原型(寄生组合) */ function inheritPrototype(subType, superType) { // 创建父类原型的副本 const prototype = object(superType.prototype); // 将副本的原型的构造器指向子类 prototype.constructor = subType; // 将子类的原型指向父类的副本 subType.prototype = prototype; } /* 寄生组合式继承 */ function SuperType(name) { this.name = name; this.colors = ['red', 'blue', 'green']; } SuperType.prototype.sayName = function() { console.log(this.name); }; function SubType(name, age) { SuperType.call(this, name); this.age = age; } inheritPrototype(SubType, SuperType); SubType.prototype.sayAge = function() { console.log(this.age); };