JavaScript 继承机制的实现(待续)

2019-06-06 05:40:31刘景俊

应该赋予sayColor()函数中的this关键字的值是obj。第二个和第三个参数是字符串。它们与sayColor()函数中的参数prefix和suffix匹配,最后生成消息"The color is red, a very nice color indeed."
要与继承机制的对象冒充方法一起使用该方法,只需将前三行的赋值、调用和删除代码替换即可:

function ClassB(sColor,sName){
//this.newMethod=classA;
//this.newMethod(sColor);
//delete this.newMethod;
Class.call(this,sColor);

this.name=sName;
this.sayName=function(){
alert(this.name);
};
}

这里,想让ClassA中的关键字this等于新创建的ClassB对象,因此this是第一个参数。第二个参数sColor对两个类来说都是唯一的参数。
3.apply()方法
apply()方法有两个参数,用作this的对象和要传递给函数的参数和数组。例如:

function sayColor(sPrefix,sSuffix){
alert(sPrefix+this.color+sSuffix);
};
var obj=new Object();
obj.color="red";

//outputs "The Color is red,a very nice color indeed."
sayColor.apply(obj,new Array("The Color is ",",a very nice color indeed."));

这个例子与前面的例子相同,只是现在调用的是apply()方法。调用apply()方法时,第一个参数仍是obj,说明应该赋予sayColor()中的this关键字值是obj。第二个参数是由两个字符串组成的数组,与sayColor()的参数prefix和suffix匹配。生成的消息仍是
"The Color is red,a nice color indeed."
该方法也用于替换前三行的赋值、调用和删除新方法的代码:

function ClassB(sColor,sName){

//this.newMethod=classA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this,new Array(sColor));

this.name=sName;
this.sayName=function(){
alert(this.name);
};
}

同样的,第一个参数仍是this。第二个参数是只有一个值color的数组。可以把ClassB的整个arguments对象作为第二个参数传递给apply()方法:

function ClassB(sColor,sName){

//this.newMethod=classA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this,arguments);

this.name=sName;
this.sayName=function(){
alert(this.name);
};
}

当然,只有超类中的参数顺序与子类中的参数顺序完全一致时才可以传递参数对象。如果不是,就必须创建一个单独的数组,按照正确的顺序放置参数。此外,还可以使用call()方法。