亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關于Promise中this的指向問題?

關于Promise中this的指向問題?

holdtom 2019-01-04 16:28:23
代碼class Dog {  constructor() {    this.name = 'adong';   }   start() {    this.p().then(this.say);   }   p() {    return new Promise((resolve, reject)=>{       resolve('good');     })   }      say(str) {    console.log(this);    console.log(this.name + str);   } }let dog = new Dog(); dog.start();題目描述say方法單獨調用時沒有問題的,但是在Promise的then里面再調用this就變為undefined了,哪個大神幫忙分析一下,謝謝!錯誤顯示undefined (node:5784) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined     at say (D:\NodeJS\Test\test2.js:18:22)
查看完整描述

1 回答

?
BIG陽

TA貢獻1859條經驗 獲得超6個贊

1>. 回調函數為匿名函數時,回調函數的this會指向window,需要對回調函數bind(this)。
2>. 回調函數為箭頭函數時,回調函數的this會指向他的直接上層,本例中指向dog。

查看完整回答
反對 回復 2019-01-04
  • 1 回答
  • 0 關注
  • 2166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號