javascript - 關(guān)于事件綁定時(shí)指定this的問(wèn)題,求助
問(wèn)題描述
function Tab($selector){ var _this = this;// 這種可以保證this正確,但是這樣寫(xiě)很累贅 $selector.on('click', function(){_this.switchIndex(); }); // 不兼容ie某些瀏覽器 $selector.on('click', this.switchIndex.bind(this));// 這種方式綁定會(huì)導(dǎo)致switchIndex內(nèi)部的this為$selector,除了上面那些, // 還有其他比較自然的方式嗎? $selector.on('click', this.switchIndex);}Tab.prototype = { switchIndex: function(){// ... }};
問(wèn)題解答
回答1:講真,第一種,很常見(jiàn)了,用多了也沒(méi)啥。
當(dāng)然,如果喜歡第二種,可以考慮用bind的polyfill(即在沒(méi)有bind的情況下利用call等方法來(lái)實(shí)現(xiàn)bind)。
ps: es6的話,箭頭函數(shù)就沒(méi)有這種煩惱,但正如第二種的情況,只支持高版本現(xiàn)代瀏覽器。
相關(guān)文章:
1. 老哥們求助啊2. 【求助大神】PHP初學(xué)者的學(xué)習(xí)規(guī)劃和視頻課程推薦(詳細(xì)一些)3. html5 - 表單 表格css怎么寫(xiě) 需要求助4. python - thrift 返回 TSocket read 0 bytes 求助!!!!5. list - python 求助6. python在list相加 求助7. javascript - 求助,html5如何調(diào)用攝像頭拍照??8. angular.js - angular post的Content-Type被設(shè)置,導(dǎo)致不能上傳圖片,求助!!9. javascript - 正則的截取匹配問(wèn)題求助10. php安裝lpsolve 擴(kuò)展求助
