VS2008中变量声明警告
VS2008 中的以下代码给出了“变量已定义”警告:
if (someVar) {
var a = 1;
}
else {
var a = 2;
}
警告在第二个 var a = ...
上给出。为了解决这个警告,我已经做了:
var a;
if (someVar) {
a = 1;
}
else {
a = 2;
}
但是这是正确的方法吗?
谢谢,
阿杰
The following code in VS2008 gives me a "variable is already defined" warning:
if (someVar) {
var a = 1;
}
else {
var a = 2;
}
The warning is given on the second var a = ...
. To cure this warning I have done:
var a;
if (someVar) {
a = 1;
}
else {
a = 2;
}
But is this the correct way to do it?
Thanks,
AJ
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是正确的做法。 JavaScript 中没有块作用域;只有函数作用域和全局作用域。
您还可以使用匿名函数给每个“块”功能范围,尽管在这种情况下不太实用:
作为旁注,这也是
for (var i = 0; ...)
的原因不鼓励使用var i; for (i = 0; ...)
,以避免同一函数中的 2 个连续循环都尝试声明变量我
Yes, that is the correct way to do it. There is no block scope in javascript; there is only function scope and global scope.
you could also give each "block" functional scope using anonymous functions, although it's not very practical in this case:
As a side note, this is also why
for (var i = 0; ...)
is discouraged in favor ofvar i; for (i = 0; ...)
, to avoid 2 consecutive loops in the same function both trying to declare the variablei
这取决于您之后如何使用这些变量。
如果它们与同一个对象相关,那么这是正确的方法。
如果它们与不同的对象相关,那么我会重命名变量,因为这可以防止将来出现维护问题。
It depends on how you're using those variables afterwards.
If they relate to the same object, then it's the correct way.
If they relate to different objects, then I'd rename the variables, as this would prevent maintenance issues in the future.
无论哪种方式都是完全有效且良好的(两个示例都确保使用
var
关键字声明变量),但通常最好的做法是在当前代码块的顶部声明您的变量,如第二个例子。Either way is perfectly valid and fine (both examples ensure that the variable is declared with the
var
keyword), but generally it's best practice to declare your vars at the top of the current code block, as in your second example.