天天看點

解決setTimeout中的this指向問題

在setInterval和setTimeout中傳入函數時,函數中的this會指向window對象。

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

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

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

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

解決辦法:

推薦用下面兩種寫法

  1. 将bind換成call,apply也會導緻立即執行,延遲效果會失效

    window.setTimeout(this.declare.bind(this), 2000);

  2. 使用es6中的箭頭函數,因為在箭頭函數中this是固定的。

    // 箭頭函數可以讓setTimeout裡面的this,綁定定義時所在的作用域,而不是指向運作時所在的作用域。

    // 參考:

    箭頭函數 window.setTimeout(() => this.declare(), 2000);