js中继承方式总结

//继承方式
//原型链继承
function SuperType () {
    this.property=true;
}
SuperType.prototype.getSuperValue=function(){
    return this.property;
};
function SubType(){
    this.subProperty=false;
}
//继承自SuperType
SubType.prototype=new SuperType();
SubType.getSubValue=function(){
    return this.subProperty;
};
var instance=new SubType();
alert(instance.getSuperValue());   //true



//破坏原型链的一种写法
function SuperType () {
    this.property=true;
}
SuperType.prototype.getSuperValue=function(){
    return this.property;
};
function SubType(){
    this.subProperty=false;
}
     //继承自SuperType
SubType.prototype=new SuperType();
     //在继承之后,subtype的prototype重新赋值给了一个对象字面量,打破了原型继承链
SubType.prototype={
    sayName : function(){
     alert(false);
    };
}
    //可以这样写就不会引起错误
    // SubType.prototype.sayName=function(){
    //  alert(false);
    // };
SubType.getSubValue=function(){
    return this.subProperty;
};
var instance=new SubType();
alert(instance.getSuperValue());
instance.sayName();  


//原型链的问题
//1、子代共享继承来的属性,很不方便
//2、不能解决父代的传参需求


//借用构造函数(constructor stealing)继承
function SuperType(){
    this.colors=["red","blue","yellow"];
}
function SubType(){
    //继承自SuperType
    SuperType.call(this);
}
var instance1 =new SubType();
instance1.colors.push("black");
var instance2 = new SubType();
alert(instance1.colors);  //red,blue,yellow,black
alert(instance2.colors);  //red,blue,yellow
//如何传递参数
function SuperType(name){
    this.name=name;
    this.colors=["red","blue","yellow"];
}
function SubType(){
    //继承自SuperType,顺便传递了参数
    SuperType.call(this,"nolan");
}
var instance1 =new SubType();
instance1.colors.push("black");
var instance2 = new SubType();
alert(instance1.colors);  //red,blue,yellow,black
alert(instance2.colors);  //red,blue,yellow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值