我有一个JavaScript类,必须经常发布事件。代码如下所示:
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
。构建这个的最佳方法是什么,以便我可以访问我需要的所有内容?
答案 0 :(得分:3)
您可以使用这两种方法。我认为如果你与函数自身的上下文无关,那么首先是最好的,这是更好的方法。
1)Arrow function - this.timeout = setTimeout(() => this.startWarning(), 30000);
2)Explicit Context binding - this.timeout = setTimeout(this.startWarning.bind(this), 30000);