The scope of JavaScript is mainly refers to the scope of the function, in the determination of the results of the time is very important, if not clear scope, it is likely to lead to not get the expected results, it will not be able to successfully write the program, after a series of learning and understanding, a summary of relevant knowledge, The understanding is superficial, hoped can help the needy person.
First introduce a concept: lexical analysis
JavaScript will parse function when it is created, and the function will form an active object at the time of creation,Activeobject, or AO, to give an actual example to analyze:
function T1 (age) { console.log (age); var age =; Console.log (age); Function age () {} Console.log (age); } T1 (1);
The lexical analysis steps are:
- Parse the formal parameter, this example is age, which generates an ao.age=undefined active object ==> and then assigns ao.age=1 according to the assignment.
- Parse local variables: In the third row there is a local variable, with the same name as age, and a ao.age=undefined active object is generated, and the ao.age=1 is overwritten.
- Parse function declaration expression: a function of age is declared at this time. So the active variable at this time is: Ao.age=function. Highest priority.
After the lexical analysis is finished, the function begins execution, at which point the function will first get the value from the AO, so the function is first assigned to age, so the output of the ao.age=function is:
function
24
24
This method can be used to assist in understanding the scope of JS:
1 JS default to function as scope
2 The scope of the function was created before it was executed
The scope of the 3 function has a scope chain (scoped nesting)and is also created before it is executed
function func () { var xo= ' Eric '; Lexical analysis of the time for ao.xo=undefined function inner () { Lexical analysis of the time for Ao.inner=functionconsole.log (XO); ao.xo=undefined--because there is also a definition of XO in the function, the return value within the functions is Ao.xo=undefinedvar xo= ' Tony ' } return inner; var ret = func ();
RET ();
The result of the program execution is: undefined
4 JavaScript function Internal variables must be declared in advance
function func () { console.log (xxoo); xxoo=tony;//has this sentence program output for undefined, if not this sentence will be an error } ret=func ();
Scope of JavaScript