Javascript variable scope details

  • 2020-03-30 00:48:09
  • OfStack

The scope of a variable refers to its visibility, while the lifecycle (survival) looks at a variable from another perspective.

The scope of variables in JS is divided into global variables and local variables. Those defined within functions are called local variables, and those defined outside functions are called global variables. (" variables outside a function are called global variables "is relative, and the premise discussed here is that variables explicitly declared with var, and variables not defined by var in a function are default global variables, of course, ignoring var is not allowed to declare variables).

var glob = 4;//Declare global variables outside functions
function fun() { 
    var height = 20; //Inside the function, var is used to declare local variables
    weight = 50; //Global variables are declared without var in a function

There is no block-level scope in JS, which is contained with braces {}. Java does. Write the 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 is not visible, syntax analysis error, that is, the compilation does not pass
    System.out.println(j); //J is not visible, syntax analysis error, that is, the compilation does not pass
    System.out.println(z); //Z is visible, output 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);//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 the problem of avoiding using a for loop and declaring variables in a global scope, which can cause contamination of the global naming scope.

JS1.7, of course, put forward the let keyword declaring variables (see, the only role for statement scope.

for(let i=0;i<5;i++) { 
alert(i);//Run times error, prompt I undefined

JS1.7 requires this reference < The script type = "application/javascript; Version = "1.7 / > < / script>

Ps: firefox2+ implements JS1.7

Related articles: