2
我有一個關於JavaScript中的類定義的基本問題。讓我解釋一下我的問題,這裏是我的課(這是爲了清楚起見的簡化版本):Javascript:使用Websocket的類定義
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
的回調函數傳遞?
謝謝@ sgarcia.dev。它正在處理你的建議。我還定義了:'this.ws_cursor_onopen = ws_cursor_onopen.bind(this)' – Bulha
Great @Bulha。如果它是正確的,請將其標記爲正確答案,以便其他人可以停止檢查此問題,因爲您仍然需要答案。 –