Javascript:使用Websocket的类定义

Javascript:使用Websocket的类定义,javascript,websocket,Javascript,Websocket,我有一个关于JavaScript中类定义的基本问题。让我解释我的问题,这是我的课程(为了清晰起见,这是一个简化版本): var RemoteCursor=function(canvas\u id){ this.ws_sendjoingroup=函数(){ log('Dummy log just for debug'); } this.ws\u cursor\u onopen=函数(){ log('ws_cursor_on open:'debug'); this.ws_sendjoingroup(

我有一个关于JavaScript中类定义的基本问题。让我解释我的问题,这是我的课程(为了清晰起见,这是一个简化版本):

var RemoteCursor=function(canvas\u id){
this.ws_sendjoingroup=函数(){
log('Dummy log just for debug');
}
this.ws\u cursor\u onopen=函数(){
log('ws_cursor_on open:'debug');
this.ws_sendjoingroup();
}
this.ws\u start\u remote\u cursor=函数(){
this.ws_remote_cursor=newwebsocket('ws://localhost/ws');
this.ws\u remote\u cursor.onopen=this.ws\u cursor\u onopen;
}
}
我在HTML页面中调用此类,如下所示:


window.onload=函数(){
var cursor1=新的远程游标(“usimage_游标”);
cursor1.ws_start_remote_cursor();
}
但是当调用
onopen
回调时,函数
ws\u cursor\u onopen
中的上下文不同,
没有定义任何内容,我得到了错误:

未捕获类型错误:this.ws\u sendjoingroup不是函数

typeof(this.ws_sendjoingroup)未定义

如何在我的
RemoteCursor
实例中传递函数作为
onopen
的回调?

尝试使用,它有助于锁定此函数的值。否则,你可以用不同的结构

var RemoteCursor=function(canvas\u id){
this.ws_sendjoingroup=ws_sendjoingroup;
this.ws\u cursor\u onopen=ws\u cursor\u onopen;
this.ws\u start\u remote\u cursor=ws\u start\u remote\u cursor.bind(this);
函数ws_sendjoingroup(){
log('Dummy log just for debug');
}
函数ws_cursor_onopen(){
log('ws_cursor_on open:'debug');
ws_sendjoingroup();
}
函数ws\u start\u remote\u cursor(){
this.ws_remote_cursor=newwebsocket('ws://localhost/ws');
this.ws\u remote\u cursor.onopen=this.ws\u cursor\u onopen;
}

}
谢谢@sgarcia.dev。这正符合你的建议。我还定义了:
this.ws\u cursor\u onopen=ws\u cursor\u onopen.bind(this)
Great@Bulha。如果答案正确,请将其标记为正确答案,这样其他人就可以停止检查此问题,认为您仍然需要答案。