我有一个关于 JavaScript 中类定义的基本问题。让我解释一下我的问题,这是我的类(class)(为清楚起见,这是一个简化版本):
var RemoteCursor = function(canvas_id) {
this.ws_sendjoingroup = function() {
console.log('Dummy log just for debug');
}
this.ws_cursor_onopen = function() {
console.log('ws_cursor_on open: (debug)');
this.ws_sendjoingroup();
}
this.ws_start_remote_cursor = function() {
this.ws_remote_cursor = new WebSocket('ws://localhost/ws');
this.ws_remote_cursor.onopen = this.ws_cursor_onopen;
}
}
我在我的 HTML 页面中这样调用这个类:
<script>
window.onload = function() {
var cursor1 = new RemoteCursor("usimage_cursor");
cursor1.ws_start_remote_cursor();
}
</script>
但是当 onopen
回调触发时,在函数 ws_cursor_onopen
中上下文不同,this
没有定义,我得到了错误:
Uncaught TypeError: this.ws_sendjoingroup is not a function!
The typeof(this.ws_sendjoingroup) is undefined
如何在我的 RemoteCursor
实例中传递该函数作为 onopen
的回调?
最佳答案
尝试使用 bind() ,它有助于锁定 this 的值。否则你可以稍微改变一下它的结构;
var RemoteCursor = function(canvas_id) {
this.ws_sendjoingroup = ws_sendjoingroup;
this.ws_cursor_onopen = ws_cursor_onopen;
this.ws_start_remote_cursor = ws_start_remote_cursor.bind(this);
function ws_sendjoingroup() {
console.log('Dummy log just for debug');
}
function ws_cursor_onopen() {
console.log('ws_cursor_on open: (debug)');
ws_sendjoingroup();
}
function ws_start_remote_cursor() {
this.ws_remote_cursor = new WebSocket('ws://localhost/ws');
this.ws_remote_cursor.onopen = this.ws_cursor_onopen;
}
}
另外,请注意,在 JavaScript 中使用继承和 OOP 编程通常效果不佳,并且是更有经验的开发人员不赞成的做法。您可以通过 D. Crockford 的精彩演讲 The Better Parts 了解更多信息 here .
关于Javascript:使用 Websocket 的类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834198/