DIV CSS 佈局教程網

原生 JavaScript 中 bind 函數的實作原理拆解
編輯:關於JavaScript     

近來又把 bind 的實作翻了一遍,順道釐清了 shim 與 polyfill 這兩個說法,在此做個整理。

 if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // 盡可能貼近 ECMAScript 5 的 IsCallable 內部判斷
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis ? this : oThis || window,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

這是官方文件給出的 polyfill 版本。以下從兩個角度拆解它。

一、參數:arguments 的處理

 var aArgs = Array.prototype.slice.call(arguments, 1);

這行把 bind 收到的參數轉成真陣列並切掉第一項——也就是要綁定的 this 物件 oThis,剩下的都是「要提前塞進目標函數的參數」。

 aArgs.concat(Array.prototype.slice.call(arguments))

這行則用陣列方法把新的參數接在既有參數後面。要特別注意,這裡的 arguments 屬於被 return 出去的 fBound 函數,也就是呼叫時才產生的參數,與外層 bind 的參數並非同一份,上下兩者不能混為一談。

這正是柯裡化的味道:先把一部分參數固定下來,等真正呼叫時再補上其餘部分,兩批參數前後拼接成完整的呼叫清單。

二、上下文:this 的保存與還原

bind 存在的意義就是綁定上下文,這段程式在上下文處理上著墨最多。

 fToBind = this;

先把呼叫 bind 的那個函數存起來,接著在 fBound 內以 fToBind.apply(...) 搭配 oThis 決定 this 的歸屬,讓原函數在指定的上下文中執行。

其中 this instanceof fNOP && oThis ? this : oThis || window 這段三元運算,是為了處理「綁定後的函數被當成構造函數 new 來用」的情形:此時 this 應該指向新建立的物件,而不是原本綁定的 oThis。

接著是原型處理:

 fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();

這裡以一個空函數 fNOP 作為中介,把原函數的 prototype 間接交給 fBound,確保 fBound 在定義時的那個上下文中運作,同時保留原型鏈。

為什麼不直接寫 fBound.prototype = self.prototype?因為那樣兩個物件的 prototype 會指向同一個記憶體位置,之後任何對 fBound.prototype 的修改都會連帶改動 self.prototype,這顯然不是我們想要的。多繞一層空函數,就能有效隔離這種互相污染。

順帶一提,shim 通常指在既有 API 上補一層相容包裝、把新介面「映射」成舊環境能懂的樣子;而 polyfill 則是更進一步,在缺少該功能的環境中直接補上完整實作。上面這段程式碼屬於後者。

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