在JS中传递局部变量和全局变量的名称是不可能的? [英] Passing local variable with name of a global variable isn't possible in JS?

查看:148
本文介绍了在JS中传递局部变量和全局变量的名称是不可能的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  foo =foobar; 
var bar = function(){
var foo = foo || ;
返回foo;

bar();`

这段代码给出了一个空字符串。为什么JS不能重新分配一个与全局变量同名的局部变量?在其他编程语言中,预期的结果当然是foobar,为什么JS的行为如此?解决方案

那是因为你声明了一个具有相同名称的局部变量 - 它掩盖了全局变量。所以当你写 foo 时,你可以引用局部变量。即使您在该局部变量的声明之前写入,情况也是如此,JavaScript中的变量是函数范围的。但是,您可以使用全局变量是全局对象的属性( window )的事实:

  var foo = window.foo || ; 

window.foo 指向全局变量这里。


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?

解决方案

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):

var foo = window.foo || "";

window.foo refers to the global variable here.

这篇关于在JS中传递局部变量和全局变量的名称是不可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆