ie支援function.bind()方法實現代碼

來源:互聯網
上載者:User

前端開發人員應該很清楚 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;
};
}

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

單純不是什麼態度,而是一種滿足。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.