DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> ie支持function.bind()方法實現代碼
ie支持function.bind()方法實現代碼
編輯:關於JavaScript     
前端開發者應該很清楚 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 && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}

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

單純不是什麼態度,而是一種滿足。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved