The js running mechanism in the browser (how the js engine handles js)

The running process of JavaScript code in the V8 engine is mainly divided into three stages:

  1. Syntax analysis phase (this phase will perform grammatical analysis on the code, check the grammatical error of the code, throw an exception on the console and terminate the execution)
  2. Compilation stage. Execute context creation (creating variable objects, establishing scope chains, and determining the point of this). For each different operating environment, the V8 engine will create a new execution context.
  3. execution stage. Push the execution context created in the compilation phase into the call stack and become the running execution context. After the code execution ends, pop it off the call stack

Create a variable object (Variable Object, VO for short)

  1. Each execution context will have an associated variable object, which will save all variables and functions defined in this context
  2. In the browser, the variable object of the global environment is the window object, so all global variables and functions are created as properties and methods of the window object.
  3. The variable object of the global environment in Node is the global object
  4. In JavaScript, the environment is divided into two types: lexical environment (Lexical Environment) and variable environment (Variable Environment).
  5. The variable environment is used to record variable declarations such as var/function
  6. The lexical environment is used to record variable declarations such as let/const/class

Establish a scope chain (Scope Chain)

Through the reference of the external lexical environment, the scope can be expanded layer by layer, establishing a scope chain extending from the inside to the outside. When a variable cannot be found in its own lexical environment record, it can search for the outer layer according to the external lexical environment reference until the external lexical environment reference in the outermost lexical environment is null. This is the variable query of the scope chain .

Determine what this points to

insert image description here

Guess you like

Origin blog.csdn.net/formylovetm/article/details/127261125