ie支持function.bind方法實現代碼

前端開發者應該很清楚 Javscript 腳本的 function 函數對象可以通過 call 或 apply 方法 , 使其改變內部作用域(this)所指向的對象 , 實現更多可擴展的功能開發 。ie 原生支持 function 對象的 call 和 apply 方法,在 firefox 或其它瀏覽器下也得到支持 , 但是 call 和 apply 方法是立即作用并執行,例如:
復制代碼 代碼如下:
var func = function () {
alert(this);
}.apply(window);

當腳本解析引擎執行到這段代碼時,會立即彈出對話框并顯示 object 字符串 。我們的初衷是想定義 func 方法作用在 window 對象域上 , 并在后期調用時再執行,但是 call 和 apply 方法并不能滿足我們的初衷 , 它們會立即得到執行 。

在 google 一番技術資料后,發現 firefox 原生支持一個 bind 方法 , 該方法很好的滿足了我們的初衷,調用方法與 call 和 apply 一樣,只是定義完成后 , 在后期調用時該方法才會執行 。但是這個 bind 方法只有在 ie10 版本的瀏覽器才得到原生支持,低于該版本的瀏覽器下執行時會得到一個 undefined 的錯誤提示 。于是只好再次上網 google 解決方案,功夫不負有心人 , 我們在 firefox 的開發站找到了解決方案,那就是增加 property 原型使得所有瀏覽器都能支持 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
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}

看懂這段代碼需要點功底,我只是知道如何拿來用 , 如果哪位大牛有興趣能夠介紹一下這段源碼的原理,不勝感激,謝謝!

單純不是什么態度,而是一種滿足 。您可能感興趣的文章:讓IE8瀏覽器支持function.bind()方法Function.prototype.bind用法示例javascript中的Function.prototye.bind深入理解JS中的Function.prototype.bind()方法jQuery中的.bind()、.live()和.delegate()之間區別分析JQuery中綁定事件(bind())和移除事件(unbind())JQuery中Bind()事件用法分析jQuery事件綁定on()、bind()與delegate() 方法詳解淺談javascript中call()、apply()、bind()的用法關于Function中的bind()示例詳解

相關經驗推薦