Written questions often have running results, and most of the body size is around the scope of expansion, the following summarizes several related questions:
- The
- outer variable function can be found inside the variable inside the function (local variable) outside the outer layer is not found.
function aaa () { var a = 10;} alert (a); // error A is not defined because a is a local variable defined inside the function, the outer (global environment) cannot access the local variable according to the scope relationship. This will result in an error
var a=10 function AAA () {alert (a); function BBB () { var a=20; AAA (); } BBB (); // 10 because AAA () is executed at the time of the AAA's scope chain a=10;
- when Var does not work overtime, global variables are automatically generated (not recommended, and the VAR keyword is recommended when defining variables generally)
function aaa () { var a = B = ten; B is not defined as a global variable with VAR, so it can be accessed to }aaa () outside the function; // alert (a);//error, A is not definedalert (b); // The equivalent of a global variable can be accessed // at this time the above code is equivalent to the following code varfunction aaa () { = ten; var a = b;} aaa (); alert (a);//error alert (b);//10
3. Variable search is the nearest principle, find the nearest var definition, the nearest can not find the words in the outer look.
var a=10; function aaa () { alert (a); var a=20; } AAA (); // undefined Nearest principle find var definition, pre-parsing process
4. The precedence is equal when the parameter and local variable have the same name.
var a=10; function aaa (a) { alert (a); var a=20;} AAA (a); // because the parameters and local variables have the same precedence, the local variable 10 is found and then the local variable defined by Var
var a=10; function aaa (a) { var a=20; alert (a); } AAA (a); // the local variable overrides the parameter, so a value is the value of the local variable
var a=10; function aaa (a) { a+=3; The base type/ parameter is equivalent to a local variable, but only partially modifies the value of a, while global access remains the global value } aaa (a); alert (a); //
var a=[1,2,3];
var b=[1,2,3]; function aaa (A, b) { A.push (4);
b=[1,2,3,4]; } AAA (A, b); alert (a); // [1,2,3,4] reference type is the address of the reference, so local modification affects global values
alert (b);//[1,2,3]
Common pen Test in JS scope, running result problem