call()方法
call()方法是与经典的对象冒充方法最相似的方法。它将第一个参数作this的对象。其它参数都是直接传给函数自身。例如:
function ClassA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
}
}
function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name=sName;
this.sayName=function(){
alert(this.sayName);
}
}
var oB=new ClassB('red','redName');
oB.sayColor(); //继承了ClassA的方法。
这里,想让ClassA的关键字this等于新创建的ClassB对象,因此this是第一个参数。第二个参数sColor对两个类都是唯一的参数。
call()方法是与经典的对象冒充方法最相似的方法。它将第一个参数作this的对象。其它参数都是直接传给函数自身。例如:
function ClassA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
}
}
function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name=sName;
this.sayName=function(){
alert(this.sayName);
}
}
var oB=new ClassB('red','redName');
oB.sayColor(); //继承了ClassA的方法。
这里,想让ClassA的关键字this等于新创建的ClassB对象,因此this是第一个参数。第二个参数sColor对两个类都是唯一的参数。
本文介绍JavaScript中使用call方法实现类继承的过程与细节。通过具体示例解释如何使父类构造函数在子类中生效,并确保this指向正确对象。

被折叠的 条评论
为什么被折叠?



