解決setTimeout中的this指向問題

在setInterval和setTimeout中傳入函數(shù)時(shí),函數(shù)中的this會(huì)指向window對(duì)象。

function LateBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// Declare bloom after a delay of 2 second
LateBloomer.prototype.bloom = function() {
  // 這個(gè)寫法會(huì)報(bào) I am a beautiful flower with undefined petals!
  // 原因:在setInterval和setTimeout中傳入函數(shù)時(shí),函數(shù)中的this會(huì)指向window對(duì)象
  window.setTimeout(this.declare, 2000);
  // 如果寫成 window.setTimeout(this.declare(), 2000); 會(huì)立即執(zhí)行,就沒有延遲效果了。
};

LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' +
    this.petalCount + ' petals!');
};

var flower = new LateBloomer();
flower.bloom();  // 二秒鐘后, 調(diào)用'declare'方法

解決辦法:

推薦用下面兩種寫法

  1. 將bind換成call,apply也會(huì)導(dǎo)致立即執(zhí)行,延遲效果會(huì)失效
    window.setTimeout(this.declare.bind(this), 2000);
  2. 使用es6中的箭頭函數(shù),因?yàn)樵诩^函數(shù)中this是固定的。
    // 箭頭函數(shù)可以讓setTimeout里面的this,綁定定義時(shí)所在的作用域,而不是指向運(yùn)行時(shí)所在的作用域。
    // 參考:箭頭函數(shù)
    window.setTimeout(() => this.declare(), 2000);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容