在 JS 中不可能用全局变量的名称传递局部变量?
foo = "foobar";
var bar = function(){
var foo = foo || "";
return foo;
}
bar();`
此代码给出结果空字符串。为什么JS不能重新分配与全局变量同名的局部变量?在其他编程语言中,预期结果当然是“foobar”,为什么 JS 会这样呢?
foo = "foobar";
var bar = function(){
var foo = foo || "";
return foo;
}
bar();`
This code gives a result empty string. Why cannot JS reassign a local variable with same name as a global variable? In other programming languages the expected result is of course "foobar", why does JS behave like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为您声明了一个具有相同名称的局部变量 - 并且它掩盖了全局变量。因此,当您编写
foo
时,您引用的是局部变量。即使您在声明该局部变量之前编写它也是如此,JavaScript 中的变量是函数范围的。但是,您可以利用全局变量是全局对象 (window
) 的属性这一事实:window.foo
指的是此处的全局变量。That's because you declared a local variable with the same name - and it masks the global variable. So when you write
foo
you refer to the local variable. That's true even if you write it before the declaration of that local variable, variables in JavaScript are function-scoped. However, you can use the fact that global variables are properties of the global object (window
):window.foo
refers to the global variable here.一旦解释器看到
var foo
,它就假定foo
是一个局部变量。为什么?答案很简单:因为这就是这种语言的构造方式。 (不,它不是唯一以这种方式工作的语言)Once interpreter sees
var foo
it assumesfoo
is a local variable. Why? The answer is simple: because that's how this language has been constructed. (and no, it is not the only language that works this way)