在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); 會立即執(zhí)行楷扬,就沒有延遲效果了盟广。
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom(); // 二秒鐘后, 調用'declare'方法
解決辦法:
推薦用下面兩種寫法
- 將bind換成call,apply也會導致立即執(zhí)行,延遲效果會失效
window.setTimeout(this.declare.bind(this), 2000); - 使用es6中的箭頭函數享扔,因為在箭頭函數中this是固定的。
// 箭頭函數可以讓setTimeout里面的this植袍,綁定定義時所在的作用域惧眠,而不是指向運行時所在的作用域。
// 參考:箭頭函數
window.setTimeout(() => this.declare(), 2000);