简体   繁体   English

socket.io unqiue变量

[英]socket.io unqiue variable

io.sockets.on('connection', function (socket) {
      socket.on('something', function(data){
             var VAR1 = true;
             if(VAR1 === true){
             VAR1 = false;
             }
      });
});

Is the variable "VAR1" unique for every user who triggers the socket event "something"? 变量“ VAR1”是否对触发套接字事件“某物”的每个用户都是唯一的? Let's say that there are 1000 users will every connections to the socket event's variable start with VAR1 being true, and can others alter it? 假设有1000个用户,与套接字事件的变量的每个连接都将以VAR1为true开头,其他用户可以更改吗? Is it unique to every connections? 每个连接都唯一吗?

Your VAR1 is unique for every single .on('something') event that occurs and will be lost as soon as the event handler is over. 您的VAR1对于每个发生的每个.on('something')事件都是唯一的,一旦事件处理程序结束,它将丢失。 It is a local variable inside that event handler so a new VAR1 is created every single time the event handler is called and it will be garbage collected by Javascript as soon as the event handler has finished running. 它是该事件处理程序内部的局部变量,因此每次调用该事件处理程序时都会创建一个新的VAR1并且一旦事件处理程序运行完毕,它将被Javascript进行垃圾回收。 The next time the event handler is triggered, a new VAR1 will be created and then garbage collected. 下次触发事件处理程序时,将创建一个新的VAR1 ,然后进行垃圾回收。

Now, if you wanted it to be unique for each separate connection and last for the duration of that connection, you could declare it at a slightly different higher scope like this: 现在,如果您希望它对于每个单独的连接都是唯一的,并且在该连接的持续时间内一直保持不变,则可以在稍微更高的范围内声明它,如下所示:

io.sockets.on('connection', function (socket) {
      var VAR1 = true;
      socket.on('something', function(data){
             if(VAR1 === true){
                 VAR1 = false;
             }
      });
});

Now, a new VAR1 will be created for each socket that connects and that variable will last for the duration of that connection (because it's in a closure) and each .on('something', ...) event that occurs will be able to access a unique VAR1 for each separate socket. 现在,将为每个连接的套接字创建一个新的VAR1 ,并且该变量将在该连接的持续时间内(因为它处于关闭状态),并且发生的每个.on('something', ...)事件都将能够为每个单独的套接字访问唯一的VAR1


FYI, if you want a unique variable for a socket, you can also just add a property to the socket object iself: 仅供参考,如果您想要套接字的唯一变量,则还可以向套接字对象iself添加一个属性:

io.sockets.on('connection', function (socket) {
      socket.VAR1 = true;
      socket.on('something', function(data){
             if(socket.VAR1 === true){
                 socket.VAR1 = false;
             }
      });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM