I'm new to JS, node, and scoping as a result. I've seen many people say to never use globals and others say to use them extremely sparingly. Basically, I have a function that declares/resets variables.
function resetStuff(){
var foo = '';
var bar = false;
...
}
and a socket.io handler.
io.on('connection', function(socket){
socket.on('event1', function (data){
if (foo == 'bar') {
doStuff()
}
});
});
To me it seems like I would have to move foo
and bar
to the global scope, but is there any way to give the socket.io events access to them without doing this?
Thanks!
no, node.js has a module scope. so, every variable outside the function just module scope, not Global. ( not like js in client browser, where every variable not in a function will be in Global scope)
so, you could:
var foo,bar;
io.on ....
and also, you could define a unamed scope by using unnamed function:
(function(){
var foo,bar;
io.on ....
})();