js中的寄生组合继承

function inheritProperty(subType, superType) {
function F(){}
F.prototype = superType.prototype;
superType.prototype.constructor = subType;
subType.prototype = new F();
}

function SuperType(name) {
this.name = name;
this.colors = ['red', 'blue', 'greee'];
}

SuperType.prototype.sayName = function () {
console.log(`SuperType.prototype.sayName, this.name=${this.name}`);
}

function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}

inheritProperty(SubType, SuperType);

SubType.prototype.sayAge = function () {
console.log(`SubType.prototype.sayAge, this.age=${this.age}`);
}

const subtype2 = new SubType('fengliang', 18);
subtype2.colors.push('yellow');
subtype2.sayAge();
subtype2.sayName();
// console.log(subtype2.colors);

const subtype1 = new SubType('someone', 18);
subtype1.sayName();

寄生组合继承的原理是:将子类(这个叫法可能不太合适)的prototype属性指向父类prototype属性, 然后子类就继承了父类原型上的属性(方法也是属性)。通过父类构造函数的call方法继承父类的属性,这些属性会被实例独享

这样做的好处是:

(1)所有子类的实例都共享父类的方法或属性

(2)父类中被共享的方法和引用属性不必在子类创建实例时,在创建一份

作者:冯亮
         
能力有限,水平一般。如有错误,欢迎指正
原文地址:https://www.cnblogs.com/fengliang/p/12752435.html