研究 bind 怎麼實作的過程中,也順道搞懂了 shim 與 polyfill 這兩個名詞的含義。以下整理 MDN 官方文件提供的 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;
};
}
var aArgs = Array.prototype.slice.call(arguments, 1);
這行把傳進 bind 的參數轉成真陣列,並切掉第一個(也就是 oThis,要綁定的對象),剩下的就是要預先綁進函數的實參。
aArgs.concat(Array.prototype.slice.call(arguments))
這裡再把「呼叫 fBound 時才傳入的參數」接在預綁參數後面。要注意兩組 arguments 完全不是同一份:aArgs 來自 bind 呼叫當下,後者來自 fBound 實際被執行時。這種「先收一部分參數、之後再補齊」的行為,本質上就是柯裡化。
fToBind = this;
先把原函數存起來,接著在 fBound 內部透過 apply 把 this 導向他,這是 bind 達成「綁定上下文」目標的核心。
fNOP.prototype = this.prototype; fBound.prototype = new fNOP();
這兩行的目的是讓 fBound 繼承原函數原型上的屬性,同時又不直接共用同一個原型物件。
為什麼不直接寫 fBound.prototype = this.prototype?因為這樣一來兩個函數的原型會指向同一個位址,之後任何對 fBound.prototype 的修改都會連帶改動原函數的原型,這顯然不是我們想要的。插入一個空函數 fNOP 作為中繼,就能讓 fBound.prototype 透過原型鏈「讀得到」原型的屬性,卻擁有自己的獨立物件。
this instanceof fNOP && oThis ? this : oThis || window
這行三元運算式在處理「bind 後的函數被當建構式呼叫」的情形:如果 this 是 fNOP 的實例(代表是用 new 呼叫的),就讓 this 指向新物件,忽略 oThis;否則才套用綁定的上下文。這正是原生 bind 規格中的行為,也解釋了為何「bind 指定 this 後再用 new 呼叫會失效」。
把這幾段拼起來看,就能理解為什麼 bind 能同時處理上下文綁定、部分參數套用、以及建構式呼叫三種情境。