寄生组合式继承
//寄生组合式继承 解决方案:通过借用构造函数来继承属性; //通过原型链来继承方法。不必为了指定子类型的原型而调用超类型的构造函数,
function inheritPrototype(subType, superType) {
let protoType = Object.create(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); // Bob
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function () {
console.log(this.age); // 18
};
let instance = new SubType("Bob", 18);
instance.sayName();
instance.sayAge();