先進(jìn)一段JS代碼
function aa(){
}
aa.prototype.init=function(){
setTimeout(this.init,1000);
console.log(1);
}
new aa().init();
問(wèn)題來(lái)了:為什么這里的console.log(1)只有執(zhí)行了兩次?
第一次是首次調(diào)用函數(shù)時(shí)輸出的轧邪,在第二次的時(shí)候 setTimeout 中的 this.init 由于脫離了 aa 類所以this的指向發(fā)生了變化(指向window或global)本股,所以第二次的 setTimeout 是失敗的膜蠢,但是第二次的 console 是成功的形真。所以總共有兩次抡砂。
如果想要一直循環(huán)的話可以使用 setTimeout(this.init.bind(this), 1000);將 this.init 中的 this 綁定到 aa 上就可以保證每次都能定位到是 aa.init 了幼苛。
function aa(){
}
aa.prototype.init=function(){
var _this=this;
setTimeout(function(){
_this.init();
},1000);
console.log(2);
}
new aa().init();