2016-03-08 55 views
3

通常當我們使用this時,它指的是類。我該如何使這個指的是函數中的類?

但是在這種情況下,thisdataChannel,我怎樣才能讓this再次指VideoService?謝謝

export class VideoService { 
    dataChannel:any; 

    setupPeerConnection() { 
     this.dataChannel.onopen = this.dataChannelStateChanged; 
    } 

    dataChannelStateChanged() { 
     // here this = dataChannel, how can I let this = VideoService 
     console.log(this); 
    } 
} 

回答

4

綁定上下文明確地Function.prototype.bind

export class VideoService { 
    dataChannel:any; 

    setupPeerConnection() { 
     this.dataChannel.onopen = this.dataChannelStateChanged.bind(this); 
    } 

    dataChannelStateChanged() { 
     console.log(this); 
    } 
} 

或使用arrow function保存詞法範圍:

export class VideoService { 
    dataChannel:any; 

    setupPeerConnection() { 
     this.dataChannel.onopen =() => this.dataChannelStateChanged(); 
    } 

    dataChannelStateChanged() { 
     console.log(this); 
    } 
} 
+0

謝謝sfsq! –

5

您可以使用bind

setupPeerConnection() { 
    this.dataChannel.onopen = this.dataChannelStateChanged.bind(this); 
} 

bind創建了一個函數的與設定爲this指定對象的副本。

+0

謝謝麥克,無論你和dfsq的是正確的! –

相關問題