The scope of a variable refers to the visibility of the variable, while the life cycle (survival period) examines the variable from another perspective.
The scope of variables in JS is divided into global variables and local variables. Those defined within the function are called local variables, and those defined outside the function are called global variables. ("Things outside a function are called global variables" are relative. The premise discussed here is that variables explicitly declared with var. Variables defined without var within a function are global variables by default. Of course, declaring variables without var is frowned upon. ).
Copy the code code as follows:
var glob = 4; //Declare global variables outside the function
function fun() {
var height = 20; //The var declaration in the function is a local variable
weight = 50; //Those declared without var in the function are global variables
}
fun();
alert(weight);
There is no block-level scope in JS, which is enclosed by braces {}. There is in Java. Write the following code in the main method
Copy the code code 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 not visible, an error will be reported during syntax analysis, that is, compilation will not pass
System.out.println(j); // j is not visible, and an error will be reported during syntax analysis, that is, compilation will not pass.
System.out.println(z); // z is visible, output 20
}
But if in JS
Copy the code code 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 illustrates a problem. Avoid using for loops while declaring variables in the global scope, otherwise it will cause pollution of the global naming scope.
Of course, JS1.7 proposed the let keyword to declare variables (see https://developer.mozilla.org/cn/New_in_JavaScript_1.7), which only applies to the scope of the for statement.
Copy the code code as follows:
for(let i=0;i<5;i++) {
//todo
}
alert(i);//An error occurs when running, indicating that i is not defined
JS1.7 needs to be referenced like this <script type="application/javascript;version=1.7"/></script>
ps: firefox2+ implements JS1.7