0
我有一個JavaScript類,必須經常發佈事件。代碼如下所示:訪問setTimeout函數中的類變量
class TimerService {
constructor(BroadcastService) {
this.Broadcast = BroadcastService;
this.timeout;
this.warningTimer;
this.startTimer();
}
startTimer() {
clearTimeout(this.timeout);
clearTimeout(this.warningTimer);
this.timeout = setTimeout(this.startWarning, 30000);
}
startWarning() {
this.Broadcast.send("timeout-warning");
this.warningTimer = setTimeout(this.logout, 60000);
}
logout() {
this.Broadcast.send("session-expired");
}
}
export default { service: TimerService, name: "TimerService" };
的問題是,在setTimeout的calllback功能外,this
範圍點window
所以我不能夠訪問this.Broadcast
。什麼是最好的方式來構建這個,所以我可以訪問我需要的一切?