Home >Web Front-end >JS Tutorial >Detailed explanation of Javascript variable scope_javascript skills

Detailed explanation of Javascript variable scope_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:261113browse

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 code The code is as follows:

var glob = 4;//Declare global variables outside the function
function fun() {
var height = 20; // What is declared with var in the function is a local variable
weight = 50; // What is declared without var in the function is a global variable
}
fun();
alert(weight);

There is no block-level scope in JS, that is, it is enclosed by curly brackets {}. There is in Java. Write the following code in the main method
Copy the code 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 not visible, syntax analysis reports an error, that is, compilation fails
System.out.println(j); // j is not visible, syntax analysis An error is reported, that is, the compilation does not pass.


Copy code


The code is as follows:{
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 a for loop to declare variables at the same time in the global scope, otherwise it will cause pollution of the global naming scope.

Of course, the let keyword was proposed in JS1.7 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 code


The code is as follows:

for(let i=0;i<5;i ) { //todo } alert(i);//When running, an error occurs, indicating that i is undefined
JS1.7 needs to reference

ps: firefox2 implements JS1.7
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn