DIV CSS 佈局教程網

JavaScript 的 call、apply、bind:三者關係與實戰總結
編輯:關於JavaScript     

call、apply、bind 是 JavaScript 面試與實務中出現頻率極高的三個方法。它們都繼承自 Function.prototype,作用都是處理 this 的指向問題,差別則在形式與執行時機。以下逐項拆解。

本文涵蓋:

  1. 三個方法的來源
  2. Function.prototype.call()
  3. Function.prototype.apply() 與三個實用場景
  4. Function.prototype.bind()
  5. 綁定回呼函式的物件
  6. 三者的異同總結

一、它們從哪裡來?

call、apply、bind 都繼承自 Function.prototype,屬於原型上的實例方法:

console.log(Function.prototype.hasOwnProperty('call'));  // true
console.log(Function.prototype.hasOwnProperty('apply')); // true
console.log(Function.prototype.hasOwnProperty('bind'));  // true

三個都回傳 true,證明它們確實定義在 Function.prototype 上。由於物件、函式、陣列都繼承了 Function.prototype,因此這三個方法在它們身上都能使用。

二、Function.prototype.call()

call 方法可以指定函式內部 this 的指向(也就是函式執行時所處的作用域),然後在該作用域中立即呼叫這個函式。

var keith  = { rascal: 123 };
var rascal = 456;
function a() { console.log(this.rascal); }

a();               // 456
a.call();          // 456
a.call(null);      // 456
a.call(undefined); // 456
a.call(this);      // 456
a.call(keith);     // 123

a 函式中的 this 若指向全域物件,結果是 456。可以看到:call 不帶參數,或參數為 null、undefined、this 時,等同於指向全域物件。用 call 把 this 指向 keith 之後,函式執行時所處的作用域就是 keith,結果變成 123。

call 可以接兩個參數:第一個指定 this 的指向,第二個(及之後)是要傳給原函式的參數。

function keith(a, b) { console.log(a + b); }
keith.call(null, 1, 2); // 3

第一個參數是必填的,可以是 null、undefined 或 this,但不能省略;設為這三者之一表示函式處於全域作用域。後續參數必須逐一列出——這正是 call 與 apply 的差異所在。

call 的一個典型應用是呼叫物件的原生方法,也可用於把類陣列物件轉成真陣列:

var obj = {};
console.log(obj.hasOwnProperty('toString')); // false

obj.hasOwnProperty = function() { return true; };
console.log(obj.hasOwnProperty('toString')); // true

// 借用原生方法繞過被覆寫的實作
console.log(Object.prototype.hasOwnProperty.call(obj, 'toString')); // false

hasOwnProperty 本是 obj 繼承而來的方法,一旦被覆寫就拿不到正確結果。call 可以把 hasOwnProperty 的原始定義放到 obj 上執行,這樣無論 obj 有沒有同名方法都不受影響。要注意的是,hasOwnProperty 是 Object.prototype 的原生方法,而 call 則是繼承自 Function.prototype。

三、Function.prototype.apply()

apply 的作用與 call 類似,同樣是改變 this 指向並立即執行函式。唯一的差別是它接收一個陣列作為函式執行時的參數。

apply 的第一個參數同樣是 this 要指向的物件,設為 null、undefined 或 this 時等同於全域物件。第二個參數必須是陣列,陣列的所有成員會依序作為參數傳入原函式。

function keith(a, b) { console.log(a + b); }
keith.call(null, 2, 3);    // 5
keith.apply(null, [2, 3]); // 5

3.1 找出陣列中的最大值

JavaScript 並未提供求陣列最大值的方法,但搭配 apply 與 Math.max 即可:

var a = [2, 4, 5, 7, 8, 10];
console.log(Math.max.apply(null, a));            // 10
console.log(Math.max.call(null, 2, 4, 5, 7, 8, 10)); // 10

3.2 把陣列的空元素變成 undefined

利用 apply 搭配 Array 建構函式,可以把稀疏陣列的空洞填成 undefined:

console.log(Array.apply(null, [1, , 3])); // [1, undefined, 3]

這個差異有實際影響:forEach 會跳過空元素,但不會跳過 undefined 與 null。

var a = [1, , 3];
a.forEach(function(index) { console.log(index); });        // 1, 3(跳過空洞)
Array.apply(null, a).forEach(function(index) {
    console.log(index);                                    // 1, undefined, 3
});

3.3 轉換類陣列物件

利用陣列的 slice 方法,可以把類陣列物件(例如 arguments)轉成真陣列。call 與 apply 都能做到:

console.log(Array.prototype.slice.apply({0:1, length:1})); // [1]
console.log(Array.prototype.slice.call({0:1, length:1}));   // [1]
console.log(Array.prototype.slice.apply({0:1, length:2}));  // [1, undefined]
console.log(Array.prototype.slice.call({0:1, length:2}));   // [1, undefined]

function keith(a, b, c){ return arguments; }
console.log(Array.prototype.slice.call(keith(2, 3, 4)));    // [2, 3, 4]

上面幾例的參數都是物件,回傳的卻是陣列,正好達到物件轉陣列的目的。這個手法能生效的前提是:被處理的物件必須具備 length 屬性,以及對應的數字鍵。

四、Function.prototype.bind()

bind 用於指定函式內部的 this 指向,然後回傳一個新函式。它並不會立即執行原函式。

var keith = { a: 1, count: function() { console.log(this.a++); } };
keith.count(); // 1
keith.count(); // 2
keith.count(); // 3

如果這個方法被賦值給另一個變數,呼叫時就會出錯:

var f = keith.count;
f(); // NaN

因為 this 不再指向 keith,而是 window。window.a 預設是 undefined,undefined++ 的結果就是 NaN。

用 bind 把 this 綁回 keith,或者直接呼叫,都能解決:

var f = keith.count.bind(keith);
f(); // 1
f(); // 2
f(); // 3

keith.count.bind(keith)(); // 1
keith.count.bind(keith)(); // 2

this 也可以綁到其他物件上:

var obj = { a: 100 };
var f = keith.count.bind(obj);
f(); // 100
f(); // 101
f(); // 102

bind 同樣可以傳參數。第一個參數若為 null、undefined 或 this,會把 this 指向全域環境;後續參數為呼叫時要傳入的值,形式與 call 相同:

function keith(a, b) { return a + b; }
console.log(keith.apply(null, [1, 4])); // 5
console.log(keith.call(null, 1, 4));    // 5
console.log(keith.bind(null, 1, 4));    // 回傳函式本身
console.log(keith.bind(null, 1, 4)());  // 5

由此可見三者最基本的差異:call 與 apply 呼叫後立即執行;bind 呼叫後回傳原函式,需要再呼叫一次才會執行。這點有點像閉包的效果。

五、綁定回呼函式的物件

在事件回呼中使用 this 時,this 會指向觸發事件的 DOM 物件。若要讓它維持指向原本="#">物件,可以這樣處理:

var o = { f: function() { console.log(this === o); } };

$('#button').on('click', function() {
    o.f.apply(o);   // 或 o.f.call(o);
    // 或 o.f.bind(o)();
});

點擊按鈕後主控台會顯示 true。之所以要把綁定語句包在一個函式體內,是因為 apply 與 call 不僅綁定執行物件,還會立即執行函式;而 bind 不會立即執行,寫法上更靈活。

六、三者關係總結

  1. 第一個參數都是指定函式內部 this 的指向,然後依該作用域呼叫函式。
  2. 都能在呼叫時傳遞參數。call 與 bind 直接傳入,apply 則需以陣列形式傳入。
  3. call 與 apply 呼叫後立即執行函式;bind 不立即執行,需要再呼叫一次,這點近似閉包。
  4. 改變 this 指向的手段不只這三個,也可以用 that 變數固定 this 的指向。

最後補充一個現代寫法:箭頭函式沒有自己的 this,它會沿用外層作用域的 this,因此在大多數「只想保留外層 this」的場景中,箭頭函式比 bind 或 that 變數都更簡潔。不過箭頭函式不能作為建構函式使用,也不適用於需要動態 this 的物件方法,這兩點仍需依情況判斷。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved