First, the question:
Window.onload=function () {
var bar=1;
function Test () {
Console.log (bar);
}
Test ();
};
Result is 1
Window.onload=function () {
var bar=1;
function Test () {
Console.log (bar);
var bar=2;
Console.log (bar);
}
Test ();
};
The result is undefined 2
Second, the scope chain:
When you want to access a variable inside the function, first find your own internal scope There is no such variable, if not on the object to find the prototype object , or not, to the scope of the scope of the search, until the Scope where window is located
Third, JavaScript variable promotion
Although the variable bar is defined in the following, but the browser at the time of parsing, the definition of the variable is put in front, the above test function is equivalent to
function Test () {
var bar;
Console.log (bar); Undefined
bar=2;
Console.log (bar); 2
}
the definition of the function will be raised to the front
var foo=function () {
Console.log (1);
};
function foo () {
Console.log (2);
}
Foo (); Result is 1
The above code is equivalent to:
function foo () {
Console.log (2);
}
var foo;
Foo=funciton () {
Console.log (1);
}
Foo (); 1
JavaScript variable Promotion