javascript第六章2

来源:互联网 发布:美国 博士 知乎 编辑:程序博客网 时间:2024/06/05 14:06

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,


借用构造函数



原创粉丝点击