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. ).
var glob = 4;//函数外声明全局变量 function fun() { var height = 20; //函数内用var声明的是局部变量 weight = 50; //函数内不用var声明的是全局变量 } fun(); alert(weight);
There is no block-level scope in JS, which is enclosed by curly brackets {}. There is in Java. Write the following code in the main method
public static void main(String... args) { for(int i=0;i<5;i++) { } { int j=10; } int z = 20; System.out.println(i); // i不可见,语法分析时报错,即编译不通过 System.out.println(j); // j不可见,语法分析时报错,即编译不通过 System.out.println(z); // z可见,输出20 }
But if in JS
for(var i=0;i<5;i++) { } var obj = {name:"Lily"}; for(var attr in obj) { } { var j=10; } alert(i);//输出4,没有块级作用域 alert(attr); //输出name,没有块级作用域 alert(j);//输出10,没有块级作用域
This also illustrates a problem. Avoid using a for loop in the global scope and declare variables at the same time, otherwise it will cause global naming range of contamination.
Of course, the let keyword was proposed in JS1.7 to declare variables, which only applies to the scope of the for statement.
for(let i=0;i<5;i++) { //todo } alert(i);//运行时报错,提示i未定义
Example of scope of variables within js function:
<html> <head> </head> <body> <script type="text/javascript"> var a = 5; var c = 3; function t(){ var a = 6; var b = 10; document.write(a+'-----'+b); document.write(c); } t(); </script> </body> </html>
Different from PHP, if a variable is to be called in a js function, it will first be searched within the function. For example, in the example, a is equal to 6; but c cannot be found in the function body, so it will look up outside the function body. If it finds it, it will be called. If it cannot find it, it will report an error.
The above is the detailed content of How to declare JS variable scope? Detailed explanation of scope examples within functions. For more information, please follow other related articles on the PHP Chinese website!