apply 與 call 都是 Function 原型上的方法,用來呼叫函式並指定 this 的指向。兩者最大的差異在於參數的傳遞方式。
func.apply(thisArg, argsArray)
apply 的第二個參數必須是陣列或類陣列物件。
func.call(thisArg, arg1, arg2, ...)
call 從第三個參數開始,會逐一傳入函式參數。
function callMe(arg1, arg2) {
var s = "";
s += "this value: " + this;
s += "<br />";
for (var i in callMe.arguments) {
s += "arguments: " + callMe.arguments[i];
s += "<br />";
}
return s;
}
document.write(callMe(1, 2));
document.write("<br />");
document.write(callMe.apply(3, [4, 5]));
document.write("<br />");
document.write(callMe.call(3, 4, 5));
從結果可以看出,apply 與 call 都能改變函式中的 this 指向,只是參數傳遞方式不同。
以下範例展示如何使用 apply 呼叫另一個函式,並指定 this:
function zqz(a, b) {
alert(a + b);
}
function zqz_1(a, b) {
zqz.apply(zqz_1, [a, b]);
}
zqz_1(1, 2); // 3
另外,也可以使用 call:
function add(a, b) {
alert(a + b);
}
function sub(a, b) {
alert(a - b);
}
add.call(sub, 3, 1); // 4
有時候開發者會疑惑:為什麼透過 call 或 apply 改變 this 後,結果不如預期?原因通常在於 this 的指向取決於函式被呼叫的方式,而不是函式定義的位置。
例如:
function parent() {
alert(this.name);
}
function child() {
this.name = "張三";
}
var p1 = new child();
parent.call(p1); // 張三
在這個例子中,parent.call(p1) 讓 parent 中的 this 指向 p1,因此能讀取到 p1.name。
由於 apply 接受陣列參數,因此常用於以下情境:
var arr = [1, 5, 3, 9]; Math.max.apply(null, arr); // 9 Math.min.apply(null, arr); // 1
也可以用來合併陣列:
var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; Array.prototype.push.apply(arr1, arr2);
apply 與 call 的核心作用都是改變函式執行時的 this 指向。apply 適合傳遞陣列參數,call 適合逐一列舉參數。理解兩者的差異,才能在回呼函式、物件借用與參數轉換等情境中靈活運用。