Home >Web Front-end >JS Tutorial >Comprehensive analysis of JavaScript scope (with code)

Comprehensive analysis of JavaScript scope (with code)

不言
不言forward
2019-04-03 10:27:592180browse

This article brings you a comprehensive analysis of JavaScript scope (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Scope determines the life cycle and visibility of variables. Variables are invisible outside the scope.

The scope of JavaScript includes: module scope, function scope, block scope, lexical scope and global scope.

Global scope

Variables defined outside the scope of any function, block, or module have global scope. Global variables can be accessed anywhere in the program.

Creating global variables becomes more difficult when the module system is enabled, but it can still be done. You can define a variable in HTML that needs to be declared outside the function, so you can create a global variable:

<script>
  let GLOBAL_DATA = { value : 1};
</script>
console.log(GLOBAL_DATA);

Creating global variables is much easier when there is no module system. Variables declared outside functions in any file are global variables.

Global variables run throughout the entire life cycle of the program.

Another way to create global variables is to use the window global object anywhere in the program:

window.GLOBAL_DATA = { value: 1 };

This way the GLOBAL_DATA variable will be everywhere .

console.log(GLOBAL_DATA)

But you also know that this approach is bad.

Module scope

If the module is not enabled, variables declared outside all functions are global variables. In a module, variables declared outside a function are hidden and are not available in other modules unless explicitly exported.

Exports make functions or objects available to other modules. In this example, I exported a function from the module file sequence.js:

// in sequence.js
export { sequence, toList, take };

The current module can use functions or objects of other modules by importing them.

import { sequence, toList, toList } from "./sequence";

To a certain extent, we can think of the module as an automatically executed function that takes the imported data as input and then returns the exported data.

Function Scope

Function scope means that parameters and variables defined in a function are visible anywhere within the function, but not outside the function.

The following is an automatically executed function called IIFE.

(function autoexecute() {
    let x = 1;
})();
console.log(x);
//Uncaught ReferenceError: x is not defined

IIFE means immediate invocation of function expression, which is a function that runs immediately after definition.

Variables declared with var have only function scope. More importantly, variables declared with var are promoted to the top of their scope. This way they can be accessed before they are declared. Take a look at the following code:

function doSomething(){
  console.log(x);
  var x = 1;
}
doSomething(); //undefined

This kind of thing doesn't happen in let. Variables declared with let can only be accessed after they are defined.

function doSomething(){
  console.log(x);
  let x = 1;
}
doSomething();
//Uncaught ReferenceError: x is not defined

Variables declared with var can be redeclared multiple times in the same scope:

function doSomething(){
  var x = 1
  var x = 2;
  console.log(x);
}
doSomething();

Use let or const Declared variables cannot be redeclared in the same scope:

function doSomething(){
  let x = 1
  let x = 2;
}
//Uncaught SyntaxError: Identifier 'x' has already been declared

Maybe we can stop caring about this because var is starting to become obsolete.

Block scope

Block scope is defined with curly braces. It is separated by { and }.

Variables declared with let and const can be constrained by block scope and can only be accessed within the block in which they are defined.

Consider the following code regarding let block scope:

let x = 1;
{ 
  let x = 2;
}
console.log(x); //1

In contrast, var declarations are not bound by block scope:

var x = 1;
{ 
  var x = 2;
}
console.log(x); //2

Another common problem is using asynchronous operations like setTimeout() in a loop. The following loop code will display the number 5 five times.

(function run(){
    for(var i=0; i<5; i++){
        setTimeout(function logValue(){
            console.log(i);         //5
        }, 100);
    }
})();

The for loop statement with the let declaration creates a new variable each time it loops and sets it to the block scope. The next loop of code will display 0 1 2 3 4 5.

(function run(){
  for(let i=0; i<5; i++){
    setTimeout(function log(){
      console.log(i); //0 1 2 3 4
    }, 100);
  }
})();

Lexical Scope

Lexical scope is the ability of an inner function to access the outer scope in which it is defined.

Look at this code:

(function autorun(){
    let x = 1;
    function log(){
      console.log(x);
    };
    
    function run(fn){
      let x = 100;
      fn();
    }
    
    run(log);//1
})();

log The function is a closure. It references the x variable from the parent function autorun(), not the x variable in the run() function.

A closure function has access to the scope in which it was created, not its own scope. The local function scope of

autorun() is the lexical scope of the log() function.

Scope Chain

Each scope has a link to the parent scope. When using variables, JavaScript looks down the scope chain until it finds the requested variable or reaches the global scope (i.e., the end of the scope chain).
Look at the following example:

let x0 = 0;
(function autorun1(){
 let x1 = 1;
  
 (function autorun2(){
   let x2 = 2;
  
   (function autorun3(){
     let x3 = 3;
      
     console.log(x0 + " " + x1 + " " + x2 + " " + x3);//0 1 2 3
    })();
  })();
})();

Internal function autorun3() can access local x3 variables. The variables x1 and x2 and the global variable x0 can also be accessed from external functions.

If the variable is not found, it will return an error in strict mode.

"use strict";
x = 1;
console.log(x)
//Uncaught ReferenceError: x is not defined

Non-strict mode is also called "sloppy mode", which creates a global variable hastily.

x = 1;
console.log(x); //1

Summary

Variables defined in the global scope can be used anywhere in the program.

In a module, variables declared outside functions are hidden and cannot be used in other modules unless they are explicitly exported.

Function scope means that parameters and variables defined in the function are visible anywhere in the function

Variables declared with let and const Has block scope. var does not have block scope.

【Related recommendations: JavaScript video tutorial

The above is the detailed content of Comprehensive analysis of JavaScript scope (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete