What's advantage to use var in the variable declaration?
Possible Duplicate:
Why don't self-closing script tags work?
Difference between using var and not using var in JavaScript
For the code, I found it is no need to declare variable using var. the following are both working
// with var
var object = new Object();
// without var
object = new Object();
what's the difference between those two?
the key difference is if you don't use var
keyword, your variable will be global, even if you defined it in some nested function.
var
defines a scope for that variable. Using a global or not depends if you want to use your object across multiple scopes or not, but globals are strongly discouraged in favour of namespaces that reduce the global scope pollution.
if you use var in the wide javascript outside of any function is not important because
var a
it's the same with
window.a
but inside a function
var a
is a private variable of the function while a points to window.a
( global )
If you don't use the var
keyword you are declaring a global variable. If you use it, you are declaring the variable inside the current scope.
For example:
function foo() {
o = new Object();
}
foo();
alert(o); // you can access the o variable here
This is very bad because you have basically polluted the global scope.
In contrast:
function foo() {
// the o variable is accessible only inside the current scope which
// is the foo function
var o = new Object();
}
foo();
alert(o); // error => o is not accessible here
Conclusion: always specify the scope of your variables using the var
keyword.
上一篇: NodeJs中var x = 1和x = 1之间的区别是什么?
下一篇: 在变量声明中使用var有什么好处?