在 JavaScript 中使用 var 重新定义局部变量
我有一个关于 JavaScript 和局部变量的相当普遍的问题。我的问题是以下内容和如果有的话有什么区别:
function bla
{
var a = 2; // local variable
a = 3; // the local variable a gets a new value
// Would do the following line anything different
// (than simply asigning this value?)
var a = 4;
}
我想我不会得到两个名为 a 的局部变量。在其他语言中,这甚至是一个错误。那么这个有什么用呢?
I have a rather general question regarding JavaScript and local variables. My question is what is the difference between the following and if there is any:
function bla
{
var a = 2; // local variable
a = 3; // the local variable a gets a new value
// Would do the following line anything different
// (than simply asigning this value?)
var a = 4;
}
I suppose I won't get two local variables named a. In other languages this is even an error. So is there any use for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
函数内任何
var
的使用都会被提升。在同一范围内对同一变量的后续使用不会产生任何影响。它与单独的
a = 4;
具有完全相同的含义。Any use of
var
within a function is hoisted. Subsequent uses on the same variable in the same scope have no effect.It has exactly the same meaning as
a = 4;
alone.