在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'方法
解決辦法:
推薦用下面兩種寫法
- 將bind換成call,apply也會(huì)導(dǎo)致立即執(zhí)行,延遲效果會(huì)失效
window.setTimeout(this.declare.bind(this), 2000); - 使用es6中的箭頭函數(shù),因?yàn)樵诩^函數(shù)中this是固定的。
// 箭頭函數(shù)可以讓setTimeout里面的this,綁定定義時(shí)所在的作用域,而不是指向運(yùn)行時(shí)所在的作用域。
// 參考:箭頭函數(shù)
window.setTimeout(() => this.declare(), 2000);