2017-09-23 138 views
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。什麼是最好的方式來構建這個,所以我可以訪問我需要的一切?

回答

2

您可以使用這兩種方法。我認爲首先是最好的,如果你與功能自己的上下文無關,這是更可取的方法。

1)Arrow function - this.timeout = setTimeout(() => this.startWarning(), 30000);

2)Explicit Context binding - this.timeout = setTimeout(this.startWarning.bind(this), 30000);