app.all(‘/apps/:user_id/status’,
function
(req, res, next) {
// …
initial = extractVariables(req.body);
});
Why does a missing var before initial cause this problem? If you don't have the var, the local variable now becomes a global variable. Much worse is that this variable is a function, so when many users are online concurrently, the variable which is not supposed to interfere with each other becomes a shared object. That means, user A's data may be overwritten by user B's data. The logic of the program is messed up.
On stackoverflow.com, there is one question "Difference between using var and not using var in JavaScript" discusses the difference between using var and not using var before variables.
// These are both globals
var
foo = 1;
bar = 2;
function
test()
{
var
foo = 1;
// Local
bar = 2;
// Global
// Execute an anonymous function
(
function
()
{
var
wibble = 1;
// Local
foo = 2;
// Inherits from scope above (creating a closure)
moo = 3;
// Global
}())
}
The code snippet above says that if you don't use var, then the js engine will look up the scope chain until it finds the variable or hits the global scope( at which point it will create it). So if you want to declare a variable which is in current functional scope, you must use var.
Here is one tool JSLint( http://www.jslint.com/ ). It is a JS code quality analysis tool, if we copy the code snippet above into the tool, we will see the following report.
Original author : Source : http://coolshell.cn/articles/7480.html#more-7480