First , let's see the code.
var a=0;
b=1;
document.write(a);
function run(){
document.write(b);
var b=1;
}
run();
I think the result is 01
.but in fact , The result is 0undefined
.
Then I modify this code.
var a=0;
b=1;
document.write(a);
function run(){
document.write(this.b); //or document.write(window.b)
var b=1;
}
run();
Yeah, this time it runs as expected. 01
. I can't understand, WHY?
More interesting, I modify the code again .
var a=0;
b=1;
document.write(a);
function run(){
document.write(b);
//var b=1; //I comment this line
}
run();
The result is 01.
So , Can anyone explain this?
Thanks for share your viewpoints. I simplify this code
b=1;
function run(){
console.log(b); //1
}
two:
b=1;
function run(){
var b=2;
console.log(b); //2
}
three:
b=1;
function run(){
console.log(b); //undefined
var b=2;
}
When you refer to a variable within a function JS first checks if that variable is declared in the current scope, i.e., within that function. If not found it looks in the containing scope. If still not found it looks in the next scope up, and so forth until finally it reaches the global scope. (Bear in mind that you can nest functions inside each other, so that's how you get several levels of containing scope though of course your exmaple doesn't do that.)
The statement:
b=1;
without var
declares a global variable that is accessible within any function, except that then in your first function you also declare a local b
. This is called variable shadowing.
"But", you say, "I declare the local b
after document.write(b)
". Here you are running into declaration "hoisting". A variable declared anywhere in a function is treated by the JS interpreter as if it had been declared at the top of the function (i.e., it is "hoisted" to the top), but, any value assignment happens in place. So your first function is actually executed as if it was like this:
function run(){
var b; // defaults to undefined
document.write(b); // write value of local b
b=1; // set value of local b
}
In your second function when you use this.b
, you'll find that this
refers to window
, and global variables are essentially properties of window
. So you are accessing the global b
and ignoring the local one.
In your third function you don't declare a local b
at all so it references the global one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With