混合继承,又叫做伪古典继承(pseudoclassical inheritance),他就是把原型链和构造函数窃取结合在了一起,使用原型链继承属性和方法,使用构造函数窃取来得到实例属性。
//例子来源于Professional JavaScript for Web Developers,third edition ,Volume 1的209页
function SuperType(name) {
this.name=name;
this.colors=['red','blue','green'];
}
SuperType.prototype.shuohua=function () {
console.log('说话');
};
function SubType(name,age) {
//inherit properties
SuperType.call(this,name);//second call to SuperType()
this.age=age;
}
//inherit methods
SubType.prototype=new SuperType();//first call to SuperType()
//自己再加个方法
SubType.prototype.sayAge=function () {
console.log(this.age);
};
var instance1=new SubType('尼古拉斯',20);
instance1.colors.push('black');
console.log(instance1.colors);//[ 'red', 'blue', 'green', 'black' ]
instance1.shuohua();
instance1.sayAge();
console.log(instance1 instanceof SuperType);//true
console.log(instance1 instanceof SubType);//true
console.log(SuperType.prototype.isPrototypeOf(instance1));//true
It alse preserves the behavior of instanceof and isPrototypeOf() for identifying the composition of objects.
console.log(instance1.__proto__==SubType.prototype);//true
console.log(SubType.prototype.__proto__==SuperType.prototype);//true
这种混合继承也有缺点,就是SuperType被调用了2次,第一次调用的时候给SubType.prototype赋值了2个属性,即name和colors;第二次是调用SubType的构造函数的时候,这次调用再次产生了name和colors属性,不过这次是作用在了SubType的实例上,覆盖了第一次的。
这岂不是浪费吗????