我该怎么做才能引用函数中的类?

Hon*_*iao 3 javascript webrtc typescript angular

通常在我们使用时this,它指的是类.

但是,在这种情况下,thisdataChannel的,我怎么才能让thisVideoService一遍吗?谢谢

export class VideoService {
    dataChannel:any;

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

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

Mik*_*uck 5

你可以用bind.

setupPeerConnection() {
    this.dataChannel.onopen = this.dataChannelStateChanged.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

bind创建一个函数的副本,其中指定的对象设置为this.