[英]Javascript call method in another method
現在我正在嘗試用jslib實現Unity Webgl。 我對如何在另一個方法的函數中調用方法感到困惑。 我想在消息來臨時調用方法Recv(ws.onmessage)。 但是,它顯示“TypeError:this.Recv is undefined”。 你能幫我弄清楚這個來源嗎?
謝謝 !!!!!
這是我的源代碼
var ws = null;
var init_url = "";
var received_msg = "";
var error_msg = "";
var WebsocketLib = {
Hello: function(){
window.alert("Hello,world!");
},
InitSocket: function(url){
init_url = Pointer_stringify(url);
console.log("InitWebSocket: "+init_url);
ws = new WebSocket(init_url);
ws.onopen = function(evt){
console.log("Connect");
isConnected = false;
ws.send("hello");
};
ws.onclose = function(evt) {
console.log("Close");
isConnected = false;
};
ws.onmessage = function(evt) {
received_msg = evt.data;
console.log("[recv] "+received_msg);
this.Recv.call(this);
};
ws.onerror = function(evt) {
error_msg = evt.data;
console.log("[error] "+error_msg);
this.Error.call(this);
};
},
Recv: function(){
console.log("[recv] "+received_msg);
var buffer = _malloc(received_msg.length + 1);
writeStringToMemory(returnStr, buffer);
return buffer;
},
Error: function(){
console.log("[error] "+error_msg);
var buffer = _malloc(error_msg.length + 1);
writeStringToMemory(error_msg, buffer);
return buffer;
}
}
在ws.onmessage中, this
將引用ws
(因為我們在ws的方法中)而不是WebsocketLib
。
但是,在你定義處理程序的Initsocket里面, this
會正確地( 在某種意義上這就是你想要的 )引用WebsocketLib對象,所以你可以創建一個綁定函數來綁定外部的 this
值來用作this
內部事件處理程序,如下所示:
ws.onmessage = function(evt) {
received_msg = evt.data;
console.log("[recv] "+received_msg);
this.Recv.call(this);
}.bind(this);
在JavaScript中, this
行為與其他語言的行為不同。 它的值取決於函數的調用方式。 您可以在Mozilla MDN頁面中閱讀有關它的更多信息。
要解決您的具體問題,您可以:
InitSocket: function(url){
var that = this; // [1]
init_url = Pointer_stringify(url);
console.log("InitWebSocket: "+init_url);
ws = new WebSocket(init_url);
ws.onopen = function(evt){
console.log("Connect");
isConnected = false;
ws.send("hello");
};
ws.onclose = function(evt) {
console.log("Close");
isConnected = false;
};
ws.onmessage = function(evt) {
received_msg = evt.data;
console.log("[recv] "+received_msg);
that.Recv.call(that); // [2]
};
ws.onerror = function(evt) {
error_msg = evt.data;
console.log("[error] "+error_msg);
that.Error.call(that); // [2]
};
},
在第1行中,我this
變量綁定到我決定調用that
的自定義變量(但您可以根據需要調用它)。 然后在第2行,我用that
而不是this
。
里面的ws.onmessage
函數的值this
是不是指的實例WebsocketLib
,所以你需要使用這個“絕招”,並訪問正確this
使用保存在封閉的一個價值,里面的值that
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.