javascript js 什么时候需要“var”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6881415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When is "var" needed in js?
提问by Tattat
Possible Duplicate:
Difference between using var and not using var in JavaScript
sometime, I saw people doing this
有时,我看到人们这样做
for(var i=0; i< array.length; i++){
//bababa
}
but I also see people doing this...
但我也看到人们这样做...
for(i=0; i< array.length; i++){
//bababa
}
What is the different between two? Thank you.
两者有什么不同?谢谢你。
回答by aroth
The var
keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window
object). Usually this is not what you want.
该var
关键字永远不会“被需要”。但是,如果您不使用它,那么您声明的变量将在全局范围内公开(即作为window
对象的属性)。通常这不是您想要的。
Usually you only want your variable to be visible in the current scope, and this is what var
does for you. It declares the variable in the current scope only (though note that in some cases the "current scope" will coincide with the "global scope", in which case there is no difference between using var
and not using var
).
通常,您只希望您的变量在当前范围内可见,而这正是var
您要做的。它仅在当前作用域中声明变量(但请注意,在某些情况下,“当前作用域”将与“全局作用域”重合,在这种情况下,使用var
和不使用没有区别var
)。
When writing code, you should prefer this syntax:
在编写代码时,您应该更喜欢这种语法:
for(var i=0; i< array.length; i++){
//bababa
}
Or if you must, then like this:
或者,如果你必须,那么像这样:
var i;
for(i=0; i< array.length; i++){
//bababa
}
Doing it like this:
这样做:
for(i=0; i< array.length; i++){
//bababa
}
...will create a variable called i
in the global scope. If someone else happened to also be using a global i
variable, then you've just overwritten their variable.
...将创建一个i
在全局范围内调用的变量。如果其他人碰巧也在使用全局i
变量,那么您只是覆盖了他们的变量。
回答by Muad'Dib
technically, you never HAVE to use it, javascript will just go merrily on its way--using your variables even if you dont declare them ahead of time.
从技术上讲,您永远不必使用它,javascript 将继续快乐地使用您的变量,即使您没有提前声明它们。
but, in practice you should always use it when you are declaring a variable. it will make your code more readable and help you to avoid confusion, especially if you are using variables with the same name and different scope...
但是,在实践中,您应该始终在声明变量时使用它。它将使您的代码更具可读性并帮助您避免混淆,特别是如果您使用具有相同名称和不同范围的变量...
var n = 23;
function functThat( )
{
var n = 32; // "local" scope
}