這篇文章主要介紹了javascript中的Function.prototye.bind的相關(guān)資料,需要的朋友可以參考下
函數(shù)綁定(Function binding)很有可能是你在開(kāi)始使用JavaScript時(shí)最少關(guān)注的一點(diǎn),但是當(dāng)你意識(shí)到你需要一個(gè)解決方案來(lái)解決如何在另一個(gè)函數(shù)中保持this上下文的時(shí)候,你真正需要的其實(shí)就是 Function.prototype.bind(),只是你有可能仍然沒(méi)有意識(shí)到這點(diǎn)。
第一次遇到這個(gè)問(wèn)題的時(shí)候,你可能傾向于將this設(shè)置到一個(gè)變量上,這樣你可以在改變了上下文之后繼續(xù)引用到它。很多人選擇使用 self, _this 或者 context 作為變量名稱(也有人使用 that)。這些方式都是有用的,當(dāng)然也沒(méi)有什么問(wèn)題。但是其實(shí)有更好、更專用的方式。
我們真正需要解決的問(wèn)題是什么?
在下面的例子代碼中,我們可以名正言順地將上下文緩存到一個(gè)變量中:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 var myObj = { specialFunction: function () { }, anotherSpecialFunction: function () { }, getAsyncData: function (cb) { cb(); }, render: function () { var that = this; this.getAsyncData(function () { that.specialFunction(); that.anotherSpecialFunction(); }); } }; myObj.render();如果我們簡(jiǎn)單地使用 this.specialFunction() 來(lái)調(diào)用方法的話,會(huì)收到下面的錯(cuò)誤:
Uncaught TypeError: Object [object global] has no method 'specialFunction'
我們需要為回調(diào)函數(shù)的執(zhí)行保持對(duì) myObj 對(duì)象上下文的引用。 調(diào)用 that.specialFunction()讓我們能夠維持作用域上下文并且正確執(zhí)行我們的函數(shù)。 然而使用 Function.prototype.bind() 可以有更加簡(jiǎn)潔干凈的方式:
?
1 2 3 4 5 6 7 8 9 10 11 render: function () { this.getAsyncData(function () { this.specialFunction(); this.anotherSpecialFunction(); }.bind(this)); }我們剛才做了什么?
.bind()創(chuàng)建了一個(gè)函數(shù),當(dāng)這個(gè)函數(shù)在被調(diào)用的時(shí)候,它的 this 關(guān)鍵詞會(huì)被設(shè)置成被傳入的值(這里指調(diào)用bind()時(shí)傳入的參數(shù))。因此,我們傳入想要的上下文,this(其實(shí)就是 myObj),到.bind()函數(shù)中。然后,當(dāng)回調(diào)函數(shù)被執(zhí)行的時(shí)候, this 便指向 myObj 對(duì)象。
如果有興趣想知道 Function.prototype.bind() 內(nèi)部長(zhǎng)什么樣以及是如何工作的,這里有個(gè)非常簡(jiǎn)單的例子:
?
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注