This is a simple JavaScript diagram (if there are any errors please point out, thank you). There are roughly two phases, the compilation phase and the execution phase. This was briefly mentioned in the previous article JavaScript Variable Promotion Mechanisms. This article takes you through some of these concepts.

1. Compile phase

Word segmentation/lexical analysis

The process is to decompose a string of characters into meaningful blocks of code called token units. For example, var num = 1; In the current phase, it is broken down into var, num, =, 1, and whitespace, each of which is a lexical unit. Of course, whether whitespace is a valid lexical unit depends on whether whitespace is meaningful in JavaScript.

Parsing/parsing

This process mainly involves converting a stream of lexical units (arrays) into a program syntax tree (abstract syntax tree, AST) nested by elements.

Preinterpretation/code generation

This phase focuses on transforming the AST into executable code. At this stage, the variables will be promoted.

Introduce a few simple concepts:

Engine: responsible for the entire JavaScript compilation and execution process. Compiler: Responsible for parsing and code generation of JavaScript. Scope: Is responsible for collecting and maintaining a set of queries for all declared identifiers, and enforces a set of rules that determine the currently executing code's access to these identifiers.Copy the code

Ii. Execution phase

1. Executable code

JavaScript is not simply interpreted line by line, but JavaScript code is divided into blocks of executable code for execution. There are three main types of executable code in JavaScript.

  • Globally executable code
  • Function executable code
  • Eval executable code

2. JavaScript engine



The figure above shows how JavaScript is executed, but we’ll skip the details. A JS engine consists of the following parts.

  • Compiler: Responsible for parsing and code generation of JavaScript.
  • Parsers: In some engines, the interpreter mainly receives bytecode, interprets and executes it, and also relies on garbage collection, etc.
  • JIT: Converts byte or abstract syntax tree into native executable code.
  • Garbage collection, analysis tools: Responsible for garbage collection and collecting information in the engine to help improve engine performance and effectiveness.

JavaScript engine memory Heap and Call Stack

Memory Heap: Allocates memory addresses

Call Stack: Code execution

    let name = 'snail';

    function sayName(name) {
        sayNameStart(name);
    }
    function sayNameStart(name) {
        sayNameEnd(name);
    }
    function sayNameEnd(name) {
        console.log(name);
    }Copy the code

When the code is declared



When the sayName function is executed, the direct function is pushed onto the execution stack and the execution context is created





4. Execution context

Every executable code in JavaScript creates an executable context before it is interpreted and executed. There are three types of executable contexts by executable code block

  • Global executable context: Every program has one global executable code, and only one. Any code that is not inside a function is in the global execution context.
  • Function executable context: Each time a function is called, a new context is created for that function. Each function creates its own execution context when it is called.
  • Eval executable context: Eval also has its own execution context.


5. Creation of execution context

  • The pointing of this: except for the arrow function, which is determined during the editing phase, this is confirmed during the code execution phase.

1, normal function call:thisPoint to thewindow2, object method call (browser environment)thisPointer to the calling objectthisPointing to constructor instance 4,apply,call,bind:thisPoints to the binding value 5, arrow functionthis:thisRefers to the first ordinary function call in the outer layerthisCopy the code

  • Create a lexical environment
  1. Global: The external environment reference to the global environment is null, which has built-in Object/Array/, etc., prototype functions in the environment logger (associated with global objects such as the window Object), and any user-defined global variables, and the value of this points to the global Object.
  2. Module environment: Contains the bindings that the module declares at the top level and the bindings that the module explicitly imports. The external environment of the module environment is the global environment.
  3. Function environment: User-defined variables within a function are stored in the environment logger. External references can be either internal or global lexical environments of other functions

The lexical environment itself consists of two parts:

  1. An Environment Record is the actual location where variable and function declarations are stored
  2. The outer circumlocutionary means that it can access its parent Lexical Environment (i.e., scope)

For environmental loggers, there are two main types of environmental loggers:

  1. Scope of declarative environment recorder (DecarativeEnvironmentRecord) : contains the function definition, variable declarations, try… Catch, etc. This type corresponds to the set of identifiers defined by declarations contained within its scope
  2. ObjectEnvironmentRecord: A set of string identifier names created by Program objects, declarations, with statements, etc., associated with objects called their bound objects, this type corresponds to the property names of their bound objects
  • Create a variable environment: The variable environment is also a lexical environment, but the difference is that the lexical environment is used to store function declarations and variable bindings (let and const), whereas the variable environment is used only to store var variable bindings.


6. Code execution

When the browser loads some JavaScript code, the engine reads it line by line and performs the following steps:

  • Populating global memory (heap) with variable and function declarations

  • Push each function call to the call stack

  • Creates a global execution context in which global functions are executed

  • Create many tiny local execution contexts (if there are internal variables or nested functions)


Third, summary

Through this article we can briefly understand the related JavaScript code execution mechanism.

Reference: How JavaScript works