问题
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