apply 與 call
在 JavaScript 中,call 與 apply 存在的意義就是改變函式執行時的上下文,換句話說,改變函式本文中 this 的指向。
JavaScript 有「定義時上下文」與「執行時上下文」,而且上下文是可以改變的。先來個例子:
function fruits() {}
fruits.prototype = {
color: "red",
say: function () { console.log("My color is " + this.color); }
}
var apple = new fruits;
apple.say(); // My color is red
如果現在有個 banana = { color: "yellow" },我們不想幫它重新定義 say 方法,就可以借用 apple 的:
banana = { color: "yellow" };
apple.say.call(banana); // My color is yellow
apple.say.apply(banana); // My color is yellow
所以 call 與 apply 就是為了動態改變 this 而出現的:某個物件沒有某方法,但另一個物件有,就能藉此借用。
兩者的差別
作用完全相同,只是接參數的方式不同。假設有:
var func = function (arg1, arg2) {};
可以這樣呼叫:
func.call(this, arg1, arg2); func.apply(this, [arg1, arg2]);
其中 this 是你想指定的上下文,可以是任何 JavaScript 物件。call 按順序傳參,apply 則把參數放進陣列。
實務判斷很簡單:參數數量明確就用 call;數量不確定就用 apply,把參數 push 進陣列再傳入。函式內部也可以用 arguments 這個偽陣列遍歷所有參數。
常用場景
陣列拼接追加:
var array1 = [12, "foo", { name: "Joe" }, -2458];
var array2 = ["Doe", 555, 100];
Array.prototype.push.apply(array1, array2);
/* array1 = [12, "foo", {name:"Joe"}, -2458, "Doe", 555, 100] */
取陣列最大值最小值:
var numbers = [5, 458, 120, -215]; var maxInNumbers = Math.max.apply(Math, numbers); // 458 maxInNumbers = Math.max.call(Math, 5, 458, 120, -215); // 458
number 本身沒有 max 方法,但 Math 有,於是得以借用。
判斷是否為陣列(前提是 toString 沒被改寫):
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
偽陣列改用陣列方法:
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
JavaScript 中存在「偽陣列」這種結構,最典型的就是 arguments,還有 getElementsByTagName、document.childNodes 回傳的 NodeList。它們有 length,卻不能用 push、pop。透過 Array.prototype.slice.call 轉成真陣列後,就能使用所有陣列方法。
進階:用面試題串起 apply
定義一個 log 方法代理 console.log,常見解法是:
function log(msg) { console.log(msg); }
log(1); // 1
log(1, 2); // 1
基本需求沒問題,但參數個數不確定時就失效了。改用 apply 即可:
function log() { console.log.apply(console, arguments); };
log(1); // 1
log(1, 2); // 1 2
接著要求每則訊息加上 (app) 前綴:
log("hello world"); // (app)hello world
比較優雅的做法是把 arguments 轉成真陣列,再用 unshift:
function log() {
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
};
bind 詳解
bind() 與 apply、call 相似,也能改變 this 指向,但有一個關鍵差異:它會回傳一個新函式而不立即執行。MDN 的說法是,bind 建立的綁定函式在呼叫時,會以傳入 bind 的第一個參數作為 this,第二個之後的參數加上呼叫時本身的參數,依序作為原函式的參數。
單體模式中我們常用 _this、that、self 保存 this:
var foo = {
bar: 1,
eventBind: function () {
var _this = this;
$('.someClass').on('click', function (event) {
console.log(_this.bar); // 1
});
}
}
這種寫法沒問題,但用 bind 更乾淨:
var foo = {
bar: 1,
eventBind: function () {
$('.someClass').on('click', function (event) {
console.log(this.bar); // 1
}.bind(this));
}
}
這裡 bind 建立了一個函式,當 click 事件被觸發時,其 this 會被設為傳入 bind 的值(也就是 foo)。再看一個簡例:
var bar = function () { console.log(this.x); }
var foo = { x: 3 }
bar(); // undefined
var func = bar.bind(foo);
func(); // 3
有意思的問題來了:連續 bind 兩次、三次會怎樣?
var bar = function () { console.log(this.x); }
var foo = { x: 3 }
var sed = { x: 4 }
var func = bar.bind(foo).bind(sed);
func(); // ?
var fiv = { x: 5 }
var func = bar.bind(foo).bind(sed).bind(fiv);
func(); // ?
答案是兩次都輸出 3,而不是 4 與 5。原因是在 JavaScript 中,多次 bind 是無效的——bind 的實作相當於在內部包了一層 apply/call,第二次 bind 只是再包住第一次的結果,因此後續的 bind 不會生效。
三者比較
var obj = { x: 81 };
var foo = { getX: function () { return this.x; } }
console.log(foo.getX.bind(obj)()); // 81
console.log(foo.getX.call(obj)); // 81
console.log(foo.getX.apply(obj)); // 81
三個都輸出 81,但注意 bind 的後面多了一對括號。
總結
•apply、call、bind 都是用來改變函式 this 指向的;
•三者第一個參數都是 this 要指向的物件,也就是想指定的上下文;
•三者都能透過後續參數傳值;
•bind 回傳函式以便稍後呼叫,apply 與 call 則是立即執行。
換句話說:需要延後執行、當回呼使用時選 bind;需要馬上執行時選 apply 或 call,再依參數形式決定用哪一個。