To understand the scope range of a variable, you have to understand the scope chain first.
When you declare a variable with the var keyword, you add a property to the object that contains the variable.
Scope chain: Because JS is a variable of the object's properties, and the object may be another object's properties, and all objects are properties of the Window object, so the relationship of these objects can be regarded as a chain
The chain head is the object where the variable is located, and the end of the chain is the Window object
Look at the following code:
functionvarfunctionvar b;}}
The function in JS is also an object, so the object where variable A is located is t,t and in the Window object, so the scope chain of a is as follows
T--window
So B so the object is t2,t2 and contained in T, and T is in the Window object, so the scope chain of B is as follows
T2--t--window
Understand the scope of the scope chain below the start variable is analyzed
1 JavaScript a variable with no VAR is a global variable, and is a property of the Window object
function test1 () {
when executing this sentence, it will find the scope object, which is the first object in the scope chain, but there is no related VAR statement in this object
find the second object in the scope chain, that is, the global object, and there is no related VAR statement in the Global object
since there is no relevant VAR statement, JS implicitly declares the variable as var all in function;
all =;
alert (all);
}
Test1 ();
alert (all);
alert (window.all);
Variables defined within the 2 function (except functions within functions) are valid within the entire function
functionvar t = 0///for(var i = 0; i < 5; i++) {T + = i;} alert (i);} test2 ();
3 variables inside the function replace the global variable with the same name
var t = "BB" function//// and in this object there is a definition of T, so t is a local variable, it replaces the global variable T//var t = "AA"; alert (t);} Test ();
4 scopes with no blocks
if (true//var tmp = 0//
JS scope chain and variable scope