2016-05-30 84 views
0

我正在使用NW.js,以創建本地websocket客戶端。我的工作原理是,現在我正在重構我的代碼,使其更加面向對象。重新分配函數調用時出錯,爲什麼?

Websockclient.prototype.connect = function() { 
    if (!("WebSocket" in window)) { 
     alert("WebSocket is NOT supported!"); 
    } else { 
     uri = "ws://" + this.host + ":" + this.port; 
     this.ws = new WebSocket(uri); 
     this.ws.onopen = function(evt) { this.onOpen(evt); } 
    } 
}; 

Websockclient.prototype.log = function(message) { 
    if (this.logEn == true) { 
     console.log(message); 
    } 
}; 

Websockclient.prototype.onOpen = function(evt) { 
    this.log("connected"); 
    this.ws.send("Client says Hi!"); 
}; 

連接打開正確,但在Websockclient.prototype.onOpen函數調用中出現故障。錯誤輸出如下:

[31910:31910:0530/115015:ERROR:edid_parser.cc(181)] invalid EDID: human unreadable char in name chrome-extension://oimdoepkkglchafiooagncfokloigedg/app/lib/websockclient.js:29 this.ws.onopen = function(evt) { this.onOpen(evt); }

TypeError: this.onOpen is not a function at WebSocket.ws.onopen (chrome-> > extension://oimdoepkkglchafiooagncfokloigedg/app/lib/websockclient.js:29:47)

它看起來像我有以下錯誤:

this.ws.onopen = function(evt) { this.onOpen(evt); }

(注:這是系NR文件websockclient.js 29)

我認爲這個任務是不正確的,但我有點卡在這裏。有人可以請解釋我在這裏錯過了什麼。

+0

爲什麼你不只是做'this.ws.onopen = this.onOpen; '? Websockclient.prototype.onOpen只收到1個參數,它甚至被稱爲相同的,因此與包裝函數相同。 – Azamantes

+0

這是行不通的,因爲onOpen函數中的this不會引用Websockclient對象。 – Gio

+1

就像@Azamantes說的那樣,添加'this.onOpen = this.onOpen.bind(this)' – Pimmol

回答

相關問題