DIV CSS 佈局教程網

call 與 apply 的實戰場景:它到底在解決什麼問題
編輯:關於JavaScript     

讀 jQuery 外掛原始碼時,常會看到 callback.call(xxx, xxx) 這種寫法。書上說 call 與 apply 可以改變作用域,但「改變作用域」到底解決了什麼問題?什麼時候該用?這篇用幾個實際場景回答。

簡單說,call 與 apply 的作用就是改變上下文(context)。以下幾個是我最常用到的場合。

場景一:Object.prototype.toString.call()

Object.prototype.toString.call(obj);

用來準確判斷 obj 的型別。為什麼不直接 obj.toString()?因為很多物件(陣列、日期、自訂類別)都覆寫了自己的 toString(),呼叫出來的不是型別標籤。而 Object.prototype.toString 會回傳 [object Array]、[object Date]、[object Null] 這種標準字串。

這裡用 call 把 this 指向要檢查的物件,等於「借用」了 Object 原型的這支方法。

場景二:讓類陣列物件使用陣列方法

arguments 長得很像陣列,有 length、能用索引取值,但沒有 push、slice、forEach 這些方法。要把它當陣列用,就得借:

Array.prototype.push.call(arguments, extraItem);
Array.prototype.slice.call(arguments);      // 轉成真陣列
Array.prototype.forEach.call(nodeList, fn); // NodeList 同理

在 ES6 之前,這是把類陣列轉成真陣列的標準手法。現在有更清楚的寫法:

const arr = Array.from(arguments);
const arr2 = [...arguments];
const arr3 = [...document.querySelectorAll('div')];

場景三:用閉包模擬私有方法

JavaScript 沒有 private 關鍵字,早期靠 IIFE 加閉包來做:

(function () {
  var Person = function () {
    this.doSomeThing = function () {
      _privateFunction.call(this);
    };
  };

  var _privateFunction = function () {
    // 這裡的 this 透過 call 指向 Person 實例
  };

  window.Person = Person;
}).call(window);

最後那個 .call(window) 是為了明確指定 IIFE 內的 this,避免在非嚴格模式下依賴「預設指向 window」的隱含行為。

場景四:讓回呼函式繼承外層的上下文

這可能是最實用的一種。當你有一個回呼參數,而希望它執行時的 this 就是目前的物件時,用 call 或 apply 切換上下文就能省下大量重複的物件名稱。

先看不用的版本:

var Person = function () { };

Person.prototype.say = function (callback) {
  callback();          // 直接呼叫
};

Person.prototype.other = function () { };

var vincent = new Person();
vincent.say(function () {
  vincent.other();     // 必須靠外部變數名稱才能存取
});

回呼裡要呼叫同一物件的其他方法,得依賴 vincent 這個外部變數。這在物件可能被重新賦值、或在迴圈中大量建立實例時,都很容易出錯。

改用 call 之後:

var Person = function () { };

Person.prototype.say = function (callback) {
  callback.call(this);   // 把 this 傳進回呼
};

Person.prototype.other = function () { };

var vincent = new Person();
vincent.say(function () {
  this.other();          // this 就是 vincent,直接呼叫
});

回呼裡的 this 現在指向正確的物件,程式碼不必再依賴外部的變數名稱,耦合度明顯降低。

call 與 apply 怎麼選

兩者功能相同,差別只在參數形式。可以這樣記:參數數量固定、寫死了就用 call;參數本身就是一個陣列(例如要轉發 arguments)就用 apply。

fn.call(obj, a, b, c);
fn.apply(obj, [a, b, c]);
fn.apply(obj, arguments);      // 參數來源是類陣列時,apply 最省事

現代替代方案

ES6 之後,多數情境都有更直觀的寫法。

需要固定 this 時用 bind:

Person.prototype.say = function (callback) {
  callback.bind(this)();
  // 或更簡潔
  callback.call(this);
};

arrow function 直接繼承外層 this:

Person.prototype.say = function (callback) {
  // 箭頭函式的 this 就是 say 裡的 this,不必綁定
  setTimeout(() => {
    this.other();
  }, 100);
};

展開運算子取代 apply:

Math.max(...[1, 5, 3, 9]);        // 等同 Math.max.apply(null, arr)
fn(...args);

ES2015 的 Reflect 也有對應方法:Reflect.apply(fn, thisArg, argsArray) 語意更明確。

即便如此,Object.prototype.toString.call() 與 Array.prototype.slice.call() 這兩個用法在讀老程式碼時還是會不斷遇到,理解它們背後的「借用方法」思路,比記住語法更重要。

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