Passing local variable with name of a global variable isn't possible in JS?

牧云@^-^@ 提交于 2019-12-20 01:16:31

问题


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?


回答1:


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.




回答2:


Once interpreter sees var foo it assumes foo 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)



来源:https://stackoverflow.com/questions/7186171/passing-local-variable-with-name-of-a-global-variable-isnt-possible-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!