javascript variable
do we have to declare js variable like this:
var x=5;
or just simple like this
x=5;
开发者_如何学运维
what is the differences?... will it effect the functionality of the variable?...
variable_name = 5
would always put the variable_name
into the global object (which is window
in a browser)
If you are in the global context
(= not a function context) the two statements are basically the same. But if you are in a function context, var
makes sure that this variable is only declared within the current context.
So for instance:
function foobar() {
bar = 55;
}
foobar();
window.bar === 55 // true
Better:
function foobar() {
var bar = 55;
}
window.bar === 55 // false
Conclusion: always use var
within the context of a function. This avoids clobbering / overriding the global object with variables.
The var
keyword limits the scope of the variable to the current function. Leaving it off makes a global. Globals are bad and should be avoided as they are a key source of race conditions and scripts interfering with each other.
x=5
means this variable (after execution) will become global and can be accessed by all other parts in your code(and also by other javascripts).
while var x=5
will be familiar only to the block which it was declared on, (and it's descendants)
Note that although x=5
will be global, it will become global only when this line is execute!
So if you place this inside a function, it will become global only after that function is called (for the first time).
It makes no difference - with the second one (x=5;) the variable is automatically declared if it does not yet exist.
I always use the first option however.
精彩评论