javascript – 如何使这个引用函数中的类?

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

但在这种情况下,这是dataChannel,我怎么能让它再次引用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); 
    }
}

解决方法:

使用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); 
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐