熟悉前端的朋友都知道,JavaScript 函式物件可以透過 call 或 apply 方法改變內部 this 所指向的物件,从而实现更靈活的功能。IE 原生支援 call 與 apply,Firefox 等瀏覽器也都支援。但 call 與 apply 是「立即作用並執行」的,例如:
var func = function () {
alert(this);
}.apply(window);
當引擎執行到這段程式碼時,會立刻跳出提示並顯示 object 字串。但我們的初衷是想「定義 func 作用在 window 上、等到之後呼叫時才執行」,call 與 apply 顯然滿足不了——它們會馬上執行。
翻查資料後發現,Firefox 原生支援一個 bind 方法,正好滿足這個需求:呼叫方式與 call、apply 相同,只是定義完成後要等到日後呼叫時才執行。遺憾的是,這個 bind 只有在 IE10 才原生支援,低於該版本的 IE 執行時會得到 undefined 的錯誤。於是只好上網尋找解法,最後在 Firefox 開發者網站找到了方案:透過擴充 Function 原型,讓所有瀏覽器都能支援 bind:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
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,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
這段程式碼需要一點功底才能完全讀懂,我自己也是先拿來用。若哪天有高手願意講解其中原理,那就再好不過了。總之,加上這段 polyfill 後,即便在舊版 IE 上也能安心使用 bind 的優雅寫法。