简体   繁体   中英

global variable in socket.io node.js javascript not working

Really basic javascript question:

Global variables in javascript and node.js, what am I doing wrong? I've seen other posts where the answer was to return the value at the end of the function. I tried this and I still can't get the value to be altered to "5" and stay that way throughout my socket connection. Any help would be greatly appreciated!

Could it be the fact that the variable is changed in an anonymous function?

var x;

io.sockets.on('connection', function(socket){
    x = 0;
    console.log("x at first is: " + x);
    socket.on('key', function(value){//value = 5
          x = value;
          console.log("x is now + " + value);
          return x;
    })

    console.log("outside, x is " + x);

    socket.on('page', function(){
          console.log("x is unfortunately still: " + x);
    })
})

and my console log looks like this:

x at first is 0

x is now 5

outside, x is 0

x is unfortunately still: 0

That is because in console.log("outside, x is " + x) x is does not actually get set due to function scope. Try:

console.log("outside, x is " + socket);

Since x is return in your socket function.

You create new function scoped variable x with following statement: var x = value; In the function it overrides your global variable. Remove you "var" and only set x = value to access the global variable.

You've used the var keyword when you assign a new value to x , which makes that x local to the anonymous function you declare it in. It is not the same x as you have outside that function. Delete that var keyword and you'll get:

x at first is 0

x is now 5

outside, x is 0 // You should expect 0 here since you output this before the socket receives a message

x is unfortunately still: 5 // Yay! It updated (assuming the 'page' message is received after the 'key' message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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