call() 方法
call() 方法是與經典的對象冒充方法最相似的方法。它的第一個參數用作 this 的對象。其他參數都直接傳遞給函數自身。例如:
復制代碼 代碼如下:
function sayHello(sPrefix,sSuffix) {
alert(this.name + ”says“ + sPrefix + sSuffix);
};
var obj = new Object();
obj.name = "Tom";
sayHello.call(obj, "Hello ", "World.");
要與繼承機制的對象冒充方法一起使用該方法,只需將前三行的賦值、調用和刪除代碼替換即可:
復制代碼 代碼如下:
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () {
alert(this.color);
};
}
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.call(this, sColor);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
apply() 方法
apply() 方法有兩個參數,用作 this 的對象和要傳遞給函數的參數的數組。例如:
復制代碼 代碼如下:
function sayColor(sPrefix,sSuffix) {
alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
obj.color = "blue";
sayColor.apply(obj, new Array("The color is ", "a very nice color indeed."));
該方法也用于替換前三行的賦值、調用和刪除新方法的代碼:
復制代碼 代碼如下:
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.apply(this, new Array(sColor));
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
復制代碼 代碼如下:
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.apply(this, arguments);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
我們可以看到這兩個方法能夠很好的代替原始的對象冒充,使寫法上變得稍微簡單。但是這些方法的弊端是子類不能繼承父類在原型鏈上聲明的方法或屬性,針對這個問題下一篇文章將會介紹JavaScript中另一種實現繼承的方式—原型鏈繼承。
新聞熱點
疑難解答
圖片精選