This article mainly gives a detailed analysis of the scope of Javascript variables. If you need a friend, you can refer to it and hope to help you. The scope of variables refers to the visibility of variables, while the life cycle (retention period) is to examine variables from another perspective.
In JS, the scope of variables is divided into global variables and local variables. defined in the function is called local variables, and outside the function is called global variables. ("Global variables outside the function" is relative, and the premise discussed here is to use the variables explicitly declared by var. The variables not defined by var in the function are global variables by default, of course, ignoring var declaration variables is not in favor ).
The Code is as follows:
Var glob = 4; // declare a global variable outside the Function
Function fun (){
Var height = 20; // The local variable declared with var in the function
Weight = 50; // global variables are declared without var in the function
}
Fun ();
Alert (weight );
JS does not have block-level scope, that is, it is included in braces. In Java. Write the following code in the main method.
The Code is as follows:
Public static void main (String... args ){
For (int I = 0; I <5; I ++ ){
}
{
Int j = 10;
}
Int z = 20;
System. out. println (I); // I is invisible, and an error is reported during syntax analysis, that is, the compilation fails.
System. out. println (j); // j is invisible, and an error is reported during syntax analysis, that is, compilation fails.
System. out. println (z); // visible to z, output 20
}
However, if
The Code is as follows:
For (var I = 0; I <5; I ++ ){
}
Var obj = {name: "Lily "};
For (var attr in obj ){
}
{
Var j = 10;
}
Alert (I); // output 4, no block-level scope
Alert (attr); // output name, no block-level scope
Alert (j); // output 10, no block-level scope
This also indicates a problem to avoid using the for Loop in a global scope and declaring variables at the same time. Otherwise, the global naming range will be contaminated.
Of course, the let keyword declaration variable (see the https://developer.mozilla.org/cn/New_in_JavaScript_1.7) in JS1.7 only applies to the for statement range.
The Code is as follows:
For (let I = 0; I <5; I ++ ){
// Todo
}
Alert (I); // an error is reported during running, prompting that I is undefined.
JS1.7 needs to be referenced in this way Script
Ps: firefox2 + implements JS1.7