什么时候是“var”? js中需要吗?
可能的重复:
在 JavaScript 中使用 var 和不使用 var 之间的区别
有时,我看到人们这样做
for(var i=0; i< array.length; i++){
//bababa
}
,但我也看到人们这样做......
for(i=0; i< array.length; i++){
//bababa
}
两者之间有什么不同?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
var
关键字从来都不是“需要的”。但是,如果您不使用它,那么您声明的变量将在全局范围内公开(即作为window
对象上的属性)。通常这不是您想要的。通常您只希望变量在当前范围内可见,这就是
var
为您所做的。它仅在当前作用域中声明变量(但请注意,在某些情况下,“当前作用域”将与“全局作用域”一致,在这种情况下,使用var
和不使用之间没有区别var
)。编写代码时,您应该更喜欢这种语法:
或者如果必须,则像这样:
这样做:
...将在全局范围内创建一个名为
i
的变量。如果其他人碰巧也在使用全局i
变量,那么您就覆盖了他们的变量。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 thewindow
object). Usually this is not what you want.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 usingvar
and not usingvar
).When writing code, you should prefer this syntax:
Or if you must, then like this:
Doing it like this:
...will create a variable called
i
in the global scope. If someone else happened to also be using a globali
variable, then you've just overwritten their variable.从技术上讲,你永远不必使用它,JavaScript 只会愉快地继续它的方式——使用你的变量,即使你没有提前声明它们。
但是,实际上,在声明变量时应该始终使用它。它将使您的代码更具可读性并帮助您避免混淆,特别是当您使用具有相同名称和不同作用域的变量时......
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.
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...