这里只是一个例子,在浏览器中使用 websocket。将 Nodejs 与用于 Websocket 的 ws 库一起使用时也发生了同样的情况。
如果你把所有的东西都写在一个类之外,所有的处理程序都会被调用: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
}
}