这里只是一个例子,在浏览器中使用websocket。 将Nodejs与ws Library for Websocket一起使用时也是如此。
如果你把一切都写在一个类的旁边,那么所有的处理程序都会被调用: EG:
try {
var host = "ws://localhost:8080";
var socket = new WebSocket(host);
socket.onopen = function(){
// Do something
}
socket.onmessage = function(msg){ // all stuff here will be called upon receiving message
// Do something
}
socket.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
但是,如果要在类中实例化,则不会调用非处理程序
var ws = new webSocketModule();
var webSocketModule = function(){
try {
var host = "ws://localhost:8080";
this.socket = new WebSocket(host);
this.socket.onopen = function(){
// Do something
}
this.socket.onmessage = function(msg){ // None of these are called upon receiving message, however the server side will have connection message that means the websocket object is functioning just fine.
// Do something
}
this.socket.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
}
因此,我必须采用凌乱的方式将所有内容全局化吗?
添加问题
var ws = new webSocketModule();
var webSocketModule = function(){
try {
var host = "ws://localhost:8080";
this.socket = new WebSocket(host);
this.socket.onopen = function(){
// Do something
}
this.socket.onmessage = function(msg){
// Do something
}
this.socket.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
}
ws.socket.onmessage = function(msg){
// This will be called, kinda confusing
}
=============================================== ================== 添加了:
var ws = new webSocketModule(); //Explain: This is the instance in the main file
// Down below is in eg: webSocketModule.js
var webSocketModule = function(){
try {
var host = "ws://localhost:8080";
var skt = this.socket = new WebSocket(host);
skt.onopen = function(){
// Do something
}
skt.onmessage = function(msg){
// Using a local variable for socket will not make this respond
// Another side will successfully show connected and send the message
// (At least it successfully printed the console log after the socket.send)
// You have to register it like the above block "ws.socket.onmessage = ..." in the main file to make it respond
// But this and the object should be the same point of reference right?
// Seems Javascript handles it differently than JAVA or C++, is there any book that recommended that talks about how browser or NodeJS handles it? thanks.
// Do something
}
skt.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
}
答案 0 :(得分:0)
你是否在实例化你的webSocketModule?
var webSocketModule = function() { ... }
var instance = new webSocketModule();
因为您已将webSocketModule
分配给变量,所以必须先将其分配才能使用它。如果您使用了named function,则无关紧要