javascript中的Function.prototye.bind
函數(shù)綁定(Function binding)很有可能是你在開始使用JavaScript時最少關(guān)注的一點,但是當你意識到你需要一個解決方案來解決如何在另一個函數(shù)中保持this上下文的時候,你真正需要的其實就是 Function.prototype.bind(),只是你有可能仍然沒有意識到這點。
第一次遇到這個問題的時候,你可能傾向于將this設置到一個變量上,這樣你可以在改變了上下文之后繼續(xù)引用到它。很多人選擇使用 self, _this 或者 context 作為變量名稱(也有人使用 that)。這些方式都是有用的,當然也沒有什么問題。但是其實有更好、更專用的方式。
我們真正需要解決的問題是什么?
在下面的例子代碼中,我們可以名正言順地將上下文緩存到一個變量中:
var myObj = { specialFunction: function () { }, anotherSpecialFunction: function () { }, getAsyncData: function (cb) { cb(); }, render: function () { var that = this; this.getAsyncData(function () { that.specialFunction(); that.anotherSpecialFunction(); }); } }; myObj.render();
如果我們簡單地使用 this.specialFunction() 來調(diào)用方法的話,會收到下面的錯誤:
Uncaught TypeError: Object [object global] has no method 'specialFunction'
我們需要為回調(diào)函數(shù)的執(zhí)行保持對 myObj 對象上下文的引用。 調(diào)用 that.specialFunction()讓我們能夠維持作用域上下文并且正確執(zhí)行我們的函數(shù)。 然而使用 Function.prototype.bind() 可以有更加簡潔干凈的方式:
render: function () { this.getAsyncData(function () { this.specialFunction(); this.anotherSpecialFunction(); }.bind(this)); }
我們剛才做了什么?
.bind()創(chuàng)建了一個函數(shù),當這個函數(shù)在被調(diào)用的時候,它的 this 關(guān)鍵詞會被設置成被傳入的值(這里指調(diào)用bind()時傳入的參數(shù))。因此,我們傳入想要的上下文,this(其實就是 myObj),到.bind()函數(shù)中。然后,當回調(diào)函數(shù)被執(zhí)行的時候, this 便指向 myObj 對象。
如果有興趣想知道 Function.prototype.bind() 內(nèi)部長什么樣以及是如何工作的,這里有個非常簡單的例子:
Function.prototype.bind = function (scope) { var fn = this; return function () { return fn.apply(scope); }; }
還有一個非常簡單的用例:
var foo = { x: 3 } var bar = function(){ console.log(this.x); } bar(); // undefined var boundFunc = bar.bind(foo); boundFunc(); // 3
我們創(chuàng)建了一個新的函數(shù),當它被執(zhí)行的時候,它的 this 會被設置成 foo —— 而不是像我們調(diào)用 bar() 時的全局作用域。
瀏覽器支持
Browser Version support
Chrome 7
Firefox (Gecko) 4.0 (2)
Internet Explorer 9
Opera 11.60
Safari 5.1.4
正如你看到的,很不幸,F(xiàn)unction.prototype.bind 在IE8及以下的版本中不被支持,所以如果你沒有一個備用方案的話,可能在運行時會出現(xiàn)問題。
幸運的是,Mozilla Developer Network(很棒的資源庫),為沒有自身實現(xiàn) .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; }; }
適用的模式
在學習技術(shù)點的時候,我發(fā)現(xiàn)有用的不僅僅在于徹底學習和理解概念,更在于看看在手頭的工作中有沒有適用它的地方,或者比較接近它的的東西。我希望,下面的某些例子能夠適用于你的代碼或者解決你正在面對的問題。
CLICK HANDLERS(點擊處理函數(shù))
一個用途是記錄點擊事件(或者在點擊之后執(zhí)行一個操作),這可能需要我們在一個對象中存入一些信息,比如:
var logger = { x: 0, updateCount: function(){ this.x++; console.log(this.x); } }
我們可能會以下面的方式來指定點擊處理函數(shù),隨后調(diào)用 logger 對象中的 updateCount() 方法。
document.querySelector('button').addEventListener('click', function(){ logger.updateCount(); });
但是我們必須要創(chuàng)建一個多余的匿名函數(shù),來確保 updateCount()函數(shù)中的 this 關(guān)鍵字有正確的值。
我們可以使用如下更干凈的方式:
document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger));
我們巧妙地使用了方便的 .bind() 函數(shù)來創(chuàng)建一個新的函數(shù),而將它的作用域綁定為 logger 對象。
SETTIMEOUT
如果你使用過模板引擎(比如Handlebars)或者尤其使用過某些MV*框架(從我的經(jīng)驗我只能談論Backbone.js),那么你也許知道下面討論的關(guān)于在渲染模板之后立即訪問新的DOM節(jié)點時會遇到的問題。
假設我們想要實例化一個jQuery插件:
var myView = { template: '/* 一個包含 <select /> 的模板字符串*/', $el: $('#content'), afterRender: function () { this.$el.find('select').myPlugin(); }, render: function () { this.$el.html(this.template()); this.afterRender(); } } myView.render();
你或許發(fā)現(xiàn)它能正常工作——但并不是每次都行,因為里面存在著問題。這是一個競爭的問題:只有先到達的才能獲勝。有時候是渲染先到,而有時候是插件的實例化先到?!咀g者注:如果渲染過程還沒有完成(DOM Node還沒有被添加到DOM樹上),那么find(‘select')將無法找到相應的節(jié)點來執(zhí)行實例化?!?/p>
現(xiàn)在,或許并不被很多人知曉,我們可以使用基于 setTimeout() 的 slight hack來解決問題。
我們稍微改寫一下我們的代碼,就在DOM節(jié)點加載后再安全的實例化我們的jQuery插件:
afterRender: function () { this.$el.find('select').myPlugin(); }, render: function () { this.$el.html(this.template()); setTimeout(this.afterRender, 0); }
然而,我們獲得的是 函數(shù) .afterRender() 不能找到 的錯誤信息。
我們接下來要做的,就是將.bind()使用到我們的代碼中:
// afterRender: function () { this.$el.find('select').myPlugin(); }, render: function () { this.$el.html(this.template()); setTimeout(this.afterRender.bind(this), 0); } //
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
- 讓IE8瀏覽器支持function.bind()方法
- ie支持function.bind()方法實現(xiàn)代碼
- Function.prototype.bind用法示例
- 深入理解JS中的Function.prototype.bind()方法
- jQuery中的.bind()、.live()和.delegate()之間區(qū)別分析
- JQuery中綁定事件(bind())和移除事件(unbind())
- JQuery中Bind()事件用法分析
- jQuery事件綁定on()、bind()與delegate() 方法詳解
- 淺談javascript中call()、apply()、bind()的用法
- 關(guān)于Function中的bind()示例詳解
相關(guān)文章
原生js實現(xiàn)改變隨意改變div屬性style的名稱和值的結(jié)果
在本文將為大家介紹下如何用原生js和jQuery實現(xiàn)隨意改變div屬性,和重置,具體實現(xiàn)如下,感興趣的朋友可以參考下,希望對大家有所幫助2013-09-09js+數(shù)組實現(xiàn)網(wǎng)頁上顯示時間/星期幾的實用方法
在網(wǎng)頁上顯示時間(年月日/時分秒),很多新手朋友都想實現(xiàn)這樣的功能,本文整理了一些實用技巧,殺出來與大家分享,感興趣的朋友可以了解下2013-01-01