您的位置:首页 > Web前端 > JavaScript

javascript 继承

2016-08-15 15:41 281 查看
原型链:利用原型让一个引用类型继承另一个引用类型的属性和方法。

function SuperType(){
this.property=true;
}
SuperType.prototype.getSuperValue=function(){
return this.property;
};
function SubType(){
this.subproperty=false;
}
SubType.prototype=new SuperType();//继承SuperType
SubType.prototype.getSubValue=function(){
return this.subproperty;
}
var instance=new SubType();
alert(instance.getSubValue());//false
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.getSubValue=function(){
return this.subproperty;
}
//重写超类型中的方法
SubType.prototype.getSuperValue=function(){
return false;
}
var instance=new SubType();
alert(instance.getSubValue());//false
alert(instance.getSuperValue());//false

不能使用对象字面量创建原型方法。

原型链的问题:

function SuperType(){
this.colors=["red","blue","green"];
}
function SubType(){
}
//继承
SubType.prototype=new SuperType();
var instance=new SubType();
instance.colors.push("black");
alert(instance.colors);//red,blue,green,black
var instance2=new SubType();
alert(instance2.colors);//red,blue,green,black这个问题和在创建对象的时候也有,因为colors是共享属性。
借用构造函数:使用apply() 和call() 方法

function SuperType(){
this.colors=["red","blue","green"];
}
function SubType(){
//继承
SuperType.call(this);
}
var instance=new SubType();
instance.colors.push("black");
alert(instance.colors);//red,blue,green,black
var instance2=new SubType();
alert(instance2.colors);//red,blue,green
function SuperType(name){
this.name=name;
}
function SubType(){
//继承
SuperType.call(this,"Nick");
this.age=29;
}
var instance=new SubType();
alert(instance.name);//Nick
alert(instance.age);//29
组合继承:将原型链和借用构造函数的技术组合到一起。
function SuperType(name){
thia.name=name;
this.colors=["red","blue","green"];
}
SuperType.prototype.sayName=function(){
alert(this.name);
};
function SubType(name,age){
SuperType.call(this,name);
this.age=age;
}
//继承方法
SubType.prototype=new SuperType();
SubType.prototype.constructor=SubType;
SubType.prototype.sayAge=function(){
alert(this.age);
}
var instance1=new SubType("Nick",29);
instance1.colors.push("black");
alert(instance1.colors);//red,blue,green,black
instance1.sayName();//Nick
instance1.sayAge();//29
var instance2=new SubType("Greg",27);
alert(instance1.colors);//red,blue,green
instance1.sayName();//Greg
instance1.sayAge();//27
还有其他的一些继承方式比较少见的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: