What is the scope scope scope, in JS is used in the lexical scope, the so-called lexical scope is reflected in the process of writing code scope, code once written, without the implementation of the scope has been decided, this is the lexical scope in JS scope rules,

  • The function runs to access data outside the function
  • Only functions can be scoped in the entire code
  • The first thing to consider is the promotion rule
  • If there is already a name in the current scope, names outside the function are not considered (proximity principle)

The scope chain

1. The only function can be made in the js scope, so long as has the code will has a scope the global scope, the successful code with function then this function will form a new scope, how to function and function, so in this scope will be the birth of a new scope, so that all the scope listed constitute the scope chain

Variable access

  • First, see which chain the variable is in (i.e. which scope), and see if there is a definition and assignment of the variable on the chain. If there is a direct use of the variable,
  • If you do not go up the chain to find, if there is direct use, stop continuing to find
  • If not, keep looking. Until the global scope is found, if the global scope does not exist, is not defined
  • Sibling chains cannot be mixed

# Code preparsing (variable promotion)

During the execution of the program, the code is first read into memory, and all declarations are marked at this point. The so-called marking is to tell the interpreter that the name is known, and there will be no undefined errors when the name is used later. This marking process is called variable name promotion

Name Statement:

Variable name promotion: tells the interpreter that the name already exists. And only promote the variable name (there is no data corresponding to it)

Function declaration: A function declaration consists of two parts:

1. First, the function declaration tells the interpreter that the name already exists and is still in the same stage as the variable name promotion. Tell the interpreter, what is the function body corresponding to this name

  • Function declarations are different from function expressions. Function declarations are written in a separate structure without any statements. Logical judgment and other structures
  • . Functions are not followed by parentheses

By Lison Link: juejin.cn/post/686992… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.