How does global variables in JavaScript work? [duplicate]

扶醉桌前 提交于 2019-12-11 09:26:53

问题


I m a newbie to javascript. I usually program in Java. I am confused by this following code snippet.

<script>
 x = "foo";

function bar(p){
  if (p){
    document.writeln("x = " + x);
  } else {
    var x = "baz";
  }
}

bar("baz");

</script>

When I run the above code snipped its printing

 x = undefined

Why does it print undefined, since x is a global variable it should print foo right ? Can anyone explain ?


回答1:


since x is a global variable it should print foo right

It would if it wasn't shadowed by the var x = "baz"; declaration further up in your function; due to hoisting it will execute the function as if you wrote

function bar(p){
  var x; // = undefined

  if (p){
    document.writeln("x = " + x);
  } else {
    x = "baz";
  }
}

To make the code do what you want, you could simply write x = "baz"; instead of var x = "baz";.




回答2:


try this output is x = foo

var x="foo";
function bar(p){

  if (p){
    document.writeln("x = " + x);
  } else {
    x = "baz";
  }
}

bar("baz");


来源:https://stackoverflow.com/questions/22705181/how-does-global-variables-in-javascript-work

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