DIV CSS 佈局教程網

徹底搞懂 JavaScript 的 call、apply 與 bind
編輯:JavaScript綜合知識     

很多人寫 JavaScript 時對 call、apply、bind 的態度是「大概知道,但一用就亂」。其實這三者的目標完全一致:重新決定函式裡的 this 指向誰。差別只在「怎麼傳參數」和「什麼時候執行」。以下用實例把它們拆乾淨。

call 與 apply:立即呼叫,改寫 this

call(thisObj, arg1, arg2, ...) 與 apply(thisObj, [arg1, arg2, ...]) 都是每個函式都具備的非繼承方法。第一個參數相同,都是「this 要指向的物件」;唯一差異是後續參數的形式:call 逐一列舉,apply 收在一個陣列裡。

window.color = 'red';
var o = { color: "blue" };

function sayColor() {
  alert(this.color);
}

sayColor();            // red,一般函式呼叫,this 是 window
sayColor.call(this);   // red,指定 this 為 window,等於沒變
sayColor.call(window); // red,同上
sayColor.call(o);      // blue,this 被改指向 o
sayColor.apply(o);     // blue,效果與 call(o) 相同

結論:只要第一個參數換掉,函式體裡的 this 就換了主人。

bind:綁定 this,並「退還」一個新函式

bind() 是 ES5 加入的方法,它不會立刻執行函式,而是建立該函式的一個新實例,這個新函式的 this 被永久綁定到傳入的值上。

function a(y) {
  return this.x + y;
}

var o = { x: 1 };
var g = a.bind(o);

g(2); // 3

呼叫 g 時,a 就相當於被當成 o 的方法來執行;之後傳給 g 的參數,會原封不動轉交給被綁定的函式。

三者的共同點

  • 都用來改變函式的 this 指向。
  • 第一個參數都是 this 要指向的目標物件。
  • 都能透過後續參數傳值。

動手比對:同一個方法,三種呼叫

var xw = {
  name: "小王",
  gender: "男",
  age: 24,
  say: function() {
    alert(this.name + " , " + this.gender + " ,今年" + this.age);
  }
};

var xh = {
  name: "小紅",
  gender: "女",
  age: 18
};

xw.say();               // 小王 , 男 ,今年24
xw.say.call(xh);        // 小紅 , 女 ,今年18
xw.say.apply(xh);       // 小紅 , 女 ,今年18
xw.say.bind(xh)();      // 小紅 , 女 ,今年18

注意最後一行:bind 只是「準備好」一個函式,後面必須補上 () 才會真正執行。寫成 xw.say.bind(xh) 什麼都不會發生——這正是 bind 與 call/apply 最直觀的差別:後兩者是「直接呼叫」,前者是「延後呼叫」。

call 與 apply 的差別:參數怎麼排

把 say 加上兩個參數再看一次:

var xw = {
  name: "小王",
  gender: "男",
  age: 24,
  say: function(school, grade) {
    alert(this.name + " , " + this.gender + " ,今年" + this.age
          + " ,在" + school + "上" + grade);
  }
};

var xh = { name: "小紅", gender: "女", age: 18 };

xw.say.call(xh, "實驗小學", "六年級");
xw.say.apply(xh, ["實驗小學", "六年級"]);

差異一目了然:call 後面的參數與函式簽名一一對應;apply 的第二個參數是一個陣列,陣列元素依序對應函式參數。當你的參數本來就存在陣列裡(例如 arguments 或資料集合),apply 會更順手。

bind 的兩段式傳参

bind 可以像 call 那樣直接帶參數:

xw.say.bind(xh, "實驗小學", "六年級")();

但因為它回傳的仍是函式,所以也可以把參數留到呼叫時才給:

xw.say.bind(xh)("實驗小學", "六年級");

這種「部分套用」(partial application)能力,讓 bind 特別適合用在事件處理與回呼函式上——例如把某個物件的方法掛到 setTimeout 或 DOM 事件上,卻又不想讓 this 跑掉。

選用建議

  • 要馬上執行、參數是散列的 → call
  • 要馬上執行、參數是陣列 → apply
  • 要拿到一個可以隨時呼叫的新函式 → bind

順帶一提,ES6 之後有了箭頭函式與 class 方法,多數場景不再需要手動搬 this;但 callback、事件監聽與部分套用的情境裡,這三個方法依然是必修課。

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