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
return this.property;
}
SubType.prototype.getSubType=function(){
return this.subproperty;
}
重写超类型中的方法(屏蔽掉SuperType.prototype.getSuperType)
SubType.prototype.getSuperType=function(){
return false;
}
var instance=new SubType();alert(instance.ggetSuperType()); //false
通过原型链实现继承时,不能使用字面量创建原型方法,因为这样做就会重写原型链
return this.property;
}
//使用字面量添加新方法,会导致上一行代码无效(以上代码刚刚把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(){
}
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,
借用构造函数