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

后端 未结 2 977
[愿得一人]
[愿得一人] 2021-01-19 10:29
foo = \"foobar\";
var bar = function(){
    var foo = foo || \"\";
    return foo;
}
bar();`

This code gives a result empty string. Why cannot JS r

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 11:11

    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.

提交回复
热议问题