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;
}
this.bworks (as well aswindow.b), but but just plainbdoes not work before thevar b...in the function.thisandwindoware the same in that context. This could be confusing if you've seen objects created using functions and local scope, but that's because functions can be used as constructors. Also, the effect of avarstatement "rising" to the top of the scope before execution is called hoisting. This is whyvar b...is local.