一个有趣的this指向问题
起源
幾天前在實現(xiàn)一段業(yè)務(wù)邏輯的時候,寫了一段代碼,大概就是封裝了一個報告類,然后根據(jù)傳入的參數(shù)不同,獲取不同的報告。報告類代碼如下(具體業(yè)務(wù)邏輯已經(jīng)去掉,?的代碼純粹為了說明this指向問題而寫)
class ReportServer {getReport (reportType) {// 統(tǒng)一的獲取報告方法return '獲得'+ reportType +'報告'}getUserReport () {// 各自的業(yè)務(wù)處理。。。return this.getReport('用戶')}getProductReport () {// 各自的業(yè)務(wù)處理。。。return this.getReport('產(chǎn)品')}getAreaReport () {// 各自的業(yè)務(wù)處理。。。return this.getReport('地域')} } 復(fù)制代碼調(diào)用代碼
const reportType = 'user' // 傳入的參數(shù) const reportServer = new ReportServer() const reportMap = {'user': reportServer.getUserReport,'product': reportServer.getProductReport,'area': reportServer.getAreaReport } reportMap[reportType]() 復(fù)制代碼然后程序一運(yùn)行,報了一個 TypeError: this.getReport is not a function 的錯誤。看到錯誤的第一秒,我的腦袋里閃過了我是誰?我在哪?我在干什么?下一秒:不可能!ReportServer這個類里面明明有g(shù)etReport這個方法!
思考
言歸正傳,看到這個報錯,第一反應(yīng)就是this指向不對了,回憶了一下js中關(guān)于this的知識:
- 函數(shù)有所屬對象,則指向所屬對象
- 函數(shù)沒有所屬對象就指向全局對象
- 用new構(gòu)造就指向新對象
- 通過 apply 或 call 或 bind 來改變 this 的所指。
沒錯,現(xiàn)在這個情況就是屬于函數(shù)有所屬對象,但是這個對象已經(jīng)不在是reportServer,而是reportMap了,因為js中的this,是在函數(shù)真正執(zhí)行的時候才會確認(rèn)指向的。看看?的代碼,更加強(qiáng)力的說明這一點
const reportMap = {'user': reportServer.getUserReport,'product': reportServer.getProductReport,'area': reportServer.getAreaReport,'test': 'test' } class ReportServer {//...getUserReport () {// 各自的業(yè)務(wù)處理。。。console.log(this)return this.getReport('用戶')} }// 最后在執(zhí)行時,這個this: { 'user': [Function: getUserReport],'product': [Function: getProductReport],'area': [Function: getAreaReport],'test': 'test' } 復(fù)制代碼好吧,記得剛開始學(xué)習(xí)js的時候,還是有著重的去學(xué)習(xí)this這方面的知識,然而在實際開發(fā)中,還是會不經(jīng)意的出錯,幸好能第一時間反應(yīng)過來Orz。
解決
好咯,既然是this指向問題,那么用call/apply指定正確的this:
reportMap[reportType].call(reportServer) // 輸出:獲得用戶報告 復(fù)制代碼或者使用?方法
const reportMap = {'user': 'getUserReport','product': 'getProductReport','area': 'getAreaReport' }reportServer[reportMap[reportType]]() // 輸出:獲得用戶報告 復(fù)制代碼再或者,改寫為if-else的形式,當(dāng)然我最開始用hash的寫法,就是不想寫if-else (⊙﹏⊙)
Thanks!
轉(zhuǎn)載于:https://juejin.im/post/5caef2105188257111725bb6
總結(jié)
以上是生活随笔為你收集整理的一个有趣的this指向问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java_11接口
- 下一篇: 云原生产业联盟成立 蚂蚁金服当选为理事单