2016-10-03 14 views
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的回調函數傳遞?

回答

1

嘗試使用bind(),它有助於鎖定值這個。否則,你可以有點不同地構造它;

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的精彩演講「更好的零件here」瞭解更多。

+0

謝謝@ sgarcia.dev。它正在處理你的建議。我還定義了:'this.ws_cursor_onopen = ws_cursor_onopen.bind(this)' – Bulha

+0

Great @Bulha。如果它是正確的,請將其標記爲正確答案,以便其他人可以停止檢查此問題,因爲您仍然需要答案。 –