javascript第六章2

6.3继承

继承包括接口继承和实现继承。由于函数没有签名,所以没有接口继承,只支持实现继承,而且实现继承只依靠原型链来实现的。

function SuperType(){

this.property=true;

}

SuperType.prototype.getSuperValue=function(){

return this.property;

};

function SubType(){

this.subproperty=false;

}


//继承了SuperType

SubType.prototype=new SuperType();

SubType.prototype.getSubvalue=function(){

return this.subproperty;

};

var instance=new SubType();

alert(instance.getSuperValue());  //true


alert(instance instanceof Object);  //true

alert(instance instanceof SuperType);  //true

alert(instance instanceof SubType);  //true


alert(Object.prototype.isPrototypeOf(instance));  //true
alert(SuperType.prototype.isPrototypeOf(instance));  //true
alert(SubType.prototype.isPrototypeOf(instance));  //true


function SuperType(){
this.property=true;
}
SuperType.prototype.getSuperType=function(){

return this.property;

}

function SubType(){
this.subproperty=false;
}
添加新方法
SubType.prototype=new SuperType();

SubType.prototype.getSubType=function(){

return this.subproperty;

}

重写超类型中的方法(屏蔽掉SuperType.prototype.getSuperType)

SubType.prototype.getSuperType=function(){

return  false;

}

var instance=new SubType();

alert(instance.ggetSuperType());    //false



通过原型链实现继承时,不能使用字面量创建原型方法,因为这样做就会重写原型链

function SuperType(){
this.property=true;
}
SuperType.prototype.getSuperType=function(){

return this.property;

}

function SubType(){
this.subproperty=false;
}
//继承了SuperType
SubType.prototype=new SuperType();

//使用字面量添加新方法,会导致上一行代码无效(以上代码刚刚把SuperType的实例赋值给原型,紧接着又将远行替换成一个而导致的问题。由于现在的原型包含的是一个object的实例,而非SuperType的实例,因此我们设想中的原型链已经被切断---SubType和SuperType之间已经没有关系了)

SubType.prototype={

getSubValue:function(){

return this.subproperty;

},

someOtherMethod:function(){

return false;

}

};

var instance = new SubType();

alert(instance.getSuperValue());   //error



原型链的问题

function SuperType(){

var colors=["red","yellow","blue"];

}

function SubType(){

}

//继承了SuperType
SubType.prototype=new SuperType();

var instance1=new SubType();

instance1.colors.push("black");

alert(instance1.colors);  //"red,yellow,blue,black"

var instance2=new SubType();

alert(instance2.colors);  //"red,yellow,blue,black"  SubType的实例都会共享colors,


借用构造函数



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值