DIV CSS 佈局教程網

call、apply、bind 到底差在哪?一次講清楚
編輯:關於JavaScript     

JavaScript 的 this 是動態的,寫程式的過程中很容易不小心就破壞了它的指向。為了能在需要時「固定」this,語言提供了 call 與 apply;而 bind 則是另一種思路——不去改動原函式,而是產生一個新的函式。這背後牽涉到函式有「定義時的上下文」與「執行時的上下文」,而且上下文是可以被更換的。

先看一個基本例子

function person() {}
person.prototype = {
    attr: { age: 18, sex: 'girl' },
    say: function () {
        console.log("My age is " + this.attr.age);
        console.log("I am a " + this.attr.sex);
    }
};

var Marry = new person();
Marry.say();    // My age is 18 / I am a girl

用 call 改變指向

function person() {}
person.prototype = {
    attr: { age: 18, sex: 'girl' },
    say: function () {
        console.log("My age is " + this.attr.age);
        console.log("I am a " + this.attr.sex);
    }
};

var xiaoming = { attr: { age: 20, sex: 'boy' } };
var Marry = new person();

Marry.say();                    // 18 / girl
Marry.say.call(xiaoming);       // 20 / boy

共同點與差異

三者都能用來「借用」函式:把函式的上下文從原本所屬的物件,切換成指定的新物件。差別在於參數形式與執行時機。

call 接受的是參數列表,逐一傳入:

fun.call(thisArg[, arg1[, arg2[, ...]]])

function f(x, y) { console.log(x + y); }
f.call(null, 1, 1);     // 2

apply 只接受兩個參數,第二個必須是陣列(或類陣列物件如 arguments):

fun.apply(thisArg, [argsArray])

function f(x, y) { console.log(x + y); }
f.apply(null, [1, 1]);  // 2

兩者功能等價,只是傳參形式不同。實務上的判斷很簡單:參數數量明確時用 call;參數數量不固定、需要展開陣列時用 apply。函式內部也可以透過 arguments 遍歷所有傳入值。

apply 的實用場景

合併陣列:

var array1 = [12, "foo", { name: "Joe" }, -2458];
var array2 = ["Doe", 555, 100];
Array.prototype.push.apply(array1, array2);
console.log(array1);    // [12, "foo", Object, -2458, "Doe", 555, 100]

把陣列攤平成多個參數傳給函式,例如取最大值:

var numbers = [5, 458, 120, -215];
Math.max.apply(null, numbers);      // 458

為函式加上前綴日誌:

log(12, "foo", { name: "Joe" }, -2458);

function log() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('(app)');
    console.log.apply(console, args);
}
// (app) 12 foo Object {name: "Joe"} -2458

bind 的不同之處

fun.bind(thisArg[, arg1[, arg2[, ...]]])

關鍵差異:bind 回傳一個 this 已被固定的新函式,它與原函式不在同一塊記憶體位址上。因此若日後要重複使用,必須把它存進變數。call 與 apply 則是呼叫即執行、直接回傳結果。

另外,bind 的第一個參數之後所帶的參數,會成為新函式的預設參數:

function f(x, y) { console.log(x + y); }

var new_f = f.bind(null, 1, 1);   // 回傳新函式
new_f();                          // 2

需要補充的是,上述範例的 thisArg 都以 null 代替;在未指定有效上下文時,非嚴格模式下 this 會落到全域物件。

三者對照

var obj = { bar: 'Oops, this is a bad idea' };
var foo = { get: function () { return this.bar; } };

var bind = foo.get.bind(obj),
    call = foo.get.call(obj),
    apply = foo.get.apply(obj);

console.log(bind(), call, apply);
console.log(bind, call, apply);
console.log(typeof bind, typeof call, typeof apply);
console.log(typeof bind(), typeof call, typeof apply);

從輸出可以清楚看出:bind() 得到的是 function,而 call/apply 得到的是函式執行後的結果。因此當你希望改變上下文但不立即執行、而是留待回呼時使用,就該選 bind。

結論整理

  • 三者都用於改變函式的 this 指向。
  • 第一個參數都是 this 要指向的物件,也就是想指定的上下文。
  • 三者都能透過後續參數傳值。
  • bind 回傳函式,便於稍後呼叫;apply 與 call 則是立即執行。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved