在 JavaScript 裡,call、apply、bind 是 Function 原型上自帶的三個方法,核心作用都是改寫函式執行時的 this 指向,从而实现「移花接木」。本文逐一拆解三者差異,並整理幾個高頻應用場景。
call 接收一個 thisArgs 與一串參數清單:thisArgs 決定函式執行期間的 this,其餘參數原樣傳入。 thisArgs 有四種情形:
(1)不傳,或傳 null、undefined,函式中的 this 指向 window 物件。
(2)傳入另一個函式,this 指向該函式引用。
(3)傳入字串、數值、布林等原始型別,this 指向對應的包裝物件(String、Number、Boolean)。
(4)傳入物件,this 即指向該物件。
function a() {
console.log(this); // 印出 a 中的 this
}
function b() {}
var obj = { name: 'onepixel' };
a.call(); // window
a.call(null); // window
a.call(undefined); // window
a.call(1); // Number
a.call(''); // String
a.call(true); // Boolean
a.call(b); // function b(){}
a.call(obj); // Object
這正是 call 的核心能力:讓你去呼叫某個物件上「並未定義」的方法,而且該方法內部還能存取這個物件的屬性。看個例子:
var a = {
name: 'onepixel',
say: function () {
console.log("Hi, I'm function a!");
}
};
function b(name) {
console.log("Post params: " + name);
console.log("I'm " + this.name);
this.say();
}
b.call(a, 'test');
// Post params: test
// I'm onepixel
// Hi, I'm function a!
執行 b.call(a, 'test') 時,字串 test 作為參數進入函式 b,而因為 call 的緣故,b 裡的 this 被指向物件 a——等效於呼叫了 a 上的 b 方法,即使 a 從未定義過 b。
apply 與 call 唯一的差別在參數形式:第二個參數必須是陣列。但要注意,雖然你傳入的是陣列,進入函式後仍是以參數清單的形式展開:
function b(x, y, z) {
console.log(x, y, z);
}
b.apply(null, [1, 2, 3]); // 1 2 3
這個「陣列轉參數清單」的特性非常實用,下面場景二會再提到。
bind 是 ES5 新增的方法,傳參方式類似 call,但有一個關鍵差異:call/apply 會立刻執行函式,而 bind 只是回傳一個綁定好 this 的函式引用,不執行。
為什麼還需要 bind?因為事件綁定的回呼不需要我們手動呼叫,它由 JS 內部在事件觸發時執行,這時 call/apply 的「順手就執行」反而成了障礙。bind 剛好填補這個缺口:
var obj = { name: 'onepixel' };
/**
* 為 document 加上 click 監聽
* 透過 bind 把 onClick 的 this 設為 obj,並預先帶入 p1、p2
*/
document.addEventListener('click', onClick.bind(obj, 'p1', 'p2'), false);
function onClick(a, b) {
console.log(
this.name, // onepixel
a, // p1
b // p2
);
}
點擊頁面後輸出 onepixel p1 p2,說明 this 已被成功改寫。想更透徹理解,可以看它的 polyfill 實作:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this, // 這裡的 this 是被綁定的目標函式
fBound = function () {
return fToBind.apply(
// 若以 new 呼叫 fBound,則以新物件作為 this,捨棄 oThis
this instanceof fToBind ? this
// 若 oThis 無效,則退回 fBound 的呼叫者
: oThis || this,
// 把 bind 時傳入的參數與呼叫時傳入的參數合併
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
// 把目標函式的原型複製過去,因為它可能被當作建構函式使用
fBound.prototype = this.prototype;
return fBound;
};
}
JavaScript 沒有 Java、C# 那樣的 extends 關鍵字,但可以藉助 call/apply 達到類似效果:
function Animal(name, weight) {
this.name = name;
this.weight = weight;
}
function Cat() {
Animal.call(this, 'cat', '50');
// Animal.apply(this, ['cat', '50']);
this.say = function () {
console.log("I am " + this.name + ", my weight is " + this.weight);
};
}
var cat = new Cat();
cat.say(); // I am cat, my weight is 50
用 new 產生 cat 時,Cat 內的 this 指向 cat。關鍵在 Animal.call(this, 'cat', '50'):把 Cat 的 this 當作 thisArgs 傳進去,Animal 內的 this 便指向 cat,於是 Animal 裡定義的 name 與 weight 就等於定義在 cat 身上,繼承於焉成立。
先認識一個非標準但通用的概念:ArrayLike(類陣列/偽陣列)。這類物件具備陣列的部分行為,在 DOM 中早已存在,而 jQuery 的流行讓它廣為人知。它的精妙之處在於行為近似原生陣列,卻可以自由擴建自己的原型,不必污染原生 Array。
JS 中常見的類陣列有 DOM 的 NodeList 與函式內的 arguments。它們能像陣列一樣存放元素,卻沒有陣列的方法。這時就能用 call 把陣列方法「借」過來:
function test() {
console.log(
arguments instanceof Array, // false
Array.isArray(arguments) // false
);
console.log(arguments.forEach); // undefined
// 把陣列的 forEach 借來遍歷 arguments
Array.prototype.forEach.call(arguments, function (item) {
console.log(item); // 1 2 3 4
});
}
test(1, 2, 3, 4);
而 apply 的「陣列轉參數清單」特性,在這類題目上略勝一籌。例如求陣列 [1,3,4,7] 的最大值:陣列本身沒有最大值方法,而 Math.max() 需要一串參數清單。apply 一次滿足兩個需求:
var arr = [2, 3, 1, 5, 4]; Math.max.apply(null, arr); // 5
把這些技巧用進實際專案,會讓程式碼的意圖更清晰、也更耐人尋味。