//继承方式
//原型链继承
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
js中继承方式总结
最新推荐文章于 2022-07-04 09:24:03 发布