2016-03-08 57 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的是正确的! –

相关问题