define variable with/without var prefix in javascript
This question already has an answer here:
In global scope, there is no difference, unless you using it again: var my_var;
will redeclare it, while my_var;
will be simply useless expression.
There is a difference only when not in global context.
Ex1 (with var):
var x = 0;
(function(){
var x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 0
Ex2 (without var):
x = 0;
(function(){
x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 1
var
is actually (re)declaring the variable in any current scope while second form is declaring it (globally?) unless it's been declared in a containing scope before. The second form is implicitly declaring, while first form is doing so explicitly.
Thus there is no difference in global scope, for it isn't contained in any other scope.
链接地址: http://www.djcxy.com/p/17364.html