如何从更广泛的范围使用Javascript变量
我正在使用 socketio
编写一个简单的 WebSocket
应用程序。我可以在连接和消息上实现两个套接字事件。第一个将套接字作为参数(客户端),第二个将客户端发送的数据作为参数。因此,我可以这样编写它,以便在消息事件中使用套接字变量:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", function(msg){
console.log("i can use message: "+msg);
console.log("and the socket: "+soc.id);
});
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
但我想将函数分开以获得更好的可读性:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(){...
我需要在函数外部的作用域中使用 soc
变量接收套接字
。这可能吗?
I am writing a simple WebSocket
application with socketio
. There are 2 socket events that I can implement, on connect and on message. The first one takes the socket as parameter(client) and second takes the data sent from client. So I could write it this way to use the socket variable in on message event:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", function(msg){
console.log("i can use message: "+msg);
console.log("and the socket: "+soc.id);
});
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
But i want to separate my functions for better readability:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(){...
I would need to use the soc
variable in a scope outside the function that receives socket
. Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确实应该做这样的事情,而不是污染全局空间(此外,其他两个答案中给出的解决方案将无法处理两个同时连接,因为
soc
在每个连接处都被覆盖)。You should really do something like this instead of polluting the global space (moreover, the solution given in the two other answers wont be able to handle two simultaneous connections, because
soc
is overridden at each connection).在 onClientConnection 函数之外初始化
soc
。现在可以在 onClientConnect 之外访问
soc
。Initialize
soc
outside of your onClientConnection function.soc
can now be accessed outside of onClientConnect.好的,这是 websocket 具体的最终答案;
ok here is the websocket specific ultimate answer;