javascript中的原型与继承3-混合继承(Combination Inheritance)

混合继承,又叫做伪古典继承(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的实例上,覆盖了第一次的。

这岂不是浪费吗????


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值