Pay attention to “songbao write code”, selected good articles, a question of the day

Saucxs | songEagle

2020, real “rat” is not easy

In 2021, “niu” changes the world

When the wind is strong and the tide is surging, the heavy task must be bravely hoof!

Time is always your own

Every minute is also for their future matting and value-added

One, foreword

This topic covers JavaScript, Node, Vue, React, browser, HTTP, etc.

Q: What is the execution process of the JS engine

Let’s divide this into two articles.

This part is about parsing and precompiling.

The next one is the implementation phase.

A question of the Day

  • Q: Tell me more about the JS data type

  • 9. Doesn’t requestAnimationFrame smell good?

  • Q: What is your understanding of ES6 proxy?

  • Interviewer: What is the difference between “for in” and “for of”?

  • 6. How can Async/Await Async/Await Async?

  • How does VUE data binding work?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

  • 1. “How does an interview question trigger deep soul searching?”

Second, the overview

Js is a very flexible language, it is necessary to understand the execution process of JS engine for us to learn JS. I have read many convenient articles, most of which are about event loop or variable promotion, without a comprehensive analysis of the process. So feel the js implementation of the detailed process sorted out, to help better understand JS.

1.1 Basic Concepts

Js is a single-threaded language.

There is always only one thread executing JAVASCRIPT code on a page in the browser

Js is a single-threaded complaint, but code parsing is very fast and does not block parsing.

Js is executed asynchronously through an Event loop

Leaving event loops aside for the moment, let’s take a look at this code to see if we understand how the JS engine executes

console.log(person)

console.log(personFun)

var person = "saucxs";

console.log(person)

function personFun() {
    console.log(person)
    var person = "songEagle";
    console.log(person)
}

personFun()

console.log(person)
Copy the code

You can use the browser to see the output yourself

Let’s take a look at the above code first, and although many developers can basically answer it, it will be verbose.

Comprehensive analysis of js engine execution process, divided into three stages

1. Grammatical analysis

2. Pre-compilation stage

3. Execution phase

Description:

  • The browser first loads the code blocks separated by script tags in the order of JS. After the js code blocks are loaded,
  • Immediately into the three stages above,
  • And then I go to the next block in that order,
  • Three more phases,
  • Whether it’s an external script file (not loaded asynchronously) or an internal script block, it’s the same, and it’s all in the same global scope.

3. Grammatical analysis

After loading the JS code block, it will first enter the syntax analysis stage, which has the following main functions:

Analyze whether the syntax of the JS script code block is correct. If incorrect, a syntaxError will be thrown out to stop the execution of the modified JS code, and then continue to find and load the next code block; If the syntax is correct, the precompilation phase is entered.

A similar syntax error is shown below:

4. Pre-compilation stage

After the js code block passes the syntax analysis stage, the next time the syntax is correct enters the precompilation stage.

Before analyzing the precompile phase, let’s take a look at the runtime environment of JS. The runtime environment mainly consists of three kinds:

1, global environment (js code after loading, into the precompilation is to enter the global environment)

2, function environment (function call, into the function environment, different functions, different function environment)

Eval environment (not recommended because of security and performance problems)

Each entry into a different execution environment will create a corresponding execution context, so in a SECTION of JS program will generally create multiple execution context, the JS engine will stack data structure to process these executions, forming the call stack. The bottom of the stack is always the global execution context, and the top is always the current execution context.

4.1 Function call stack

What is a function call stack?

Function call stack is to use stack access to manage the operating environment, characterized by advanced back out, back in back out

Let’s take a look at the simple js code to understand the function call stack:

function bar() {
    var B_context = "bar saucxs";

    function foo() {
        var f_context = "foo saucxs";
    }

    foo()
}

bar()
Copy the code

After the above code block passes the syntax analysis, it enters the pre-compilation stage, as shown in the figure:

1. Enter the global Execution Context and push it to the stack.

2. Call the bar function, enter the running environment of the bar function, create the BAR Execution Context, and push the bar function into the stack;

3. Call foo from inside bar, then enter foo’s Execution Context, as shown in the figure above. Since no other function is called from inside foo, the stack starts to exit.

5. After the Execution of function foo, the Execution Context of function foo at the top of the stack is removed first.

6. After the Execution of the bar function is complete, the bar Execution Context is removed from the stack.

The global Execution text is removed from the stack when the browser or tag is closed.

Note: The execution of different runtime environments will enter the two stages of code precompilation and execution. Syntax analysis checks the syntax uniformly when the code block is loaded.

4.2 Creating an Execution Context

The execution context can be understood as the current execution environment, corresponding to the runtime environment. Three things are done to create an execution context, as shown in the figure below:

Create a variable object.

Create scope chain

3. Determine the direction of this

4.2.1 Creating variable Objects

Creating a variable object is done through the following process, as shown in the figure below:

1, create the arguments object, check the parameters of the current context, established the object’s properties and property values, only (not arrow function) in the environment of the function, the global environment without this process.

2, check the current context function declarations, according to the code in order to find, to find the function declaration in advance, if the current context variable object is not the function name attribute, the function name in the variable object to establish an attribute, the attribute value is pointing to the function in the heap memory address references, if present, will be covered by the new reference.

3, check the variable declaration of the current context, where to find the code sequence search, will find the variable declaration in advance, if the current context of the variable object does not have a variable name attribute, then in the variable object to create a variable name attribute, attribute value is undefined; If it exists, the variable declaration is ignored.

In the global environment, the Window object is the variable object of the global execution context. All variables and functions are the property methods of the Window object.

So function declaration advance and variable declaration promotion are carried out in the creation of variable objects, and function declaration takes precedence over variable declaration.

Let’s look at this simple code again

function fun(m,n){ var saucxs = 1; Function execution(){console.log(saucxs)}} fun(2,3)Copy the code

Here we call fun in the global environment, creating the execution context for Fun, leaving aside the scope chain and the issues this points to.

Arguments: {m: undefined, n: undefined, length: 2}, //execution function execution: <execution reference>, //num variables saucxs: undefined}, // scopeChain:[], //this points to this: window}Copy the code

FunEC is the fun Execution Context. FunEC is the fun Execution Context.

The arguments property of funEC is displayed as an array of classes in the browser

A reference to the heap memory address of the execution function

Description: The creation of the variable object occurs in the pre-compilation stage, and it has not entered the execution stage, so the variable object cannot be accessed, because the variable attribute of the variable object at this time has not been assigned, and the value is still undefined. Only during the execution stage, the variable attribute of the variable is assigned. A Variable Object can be accessed only after it is turned into an Active Object. This process is called the VO->AO procedure.

4.2.2 Creating a scope chain

The scope chain consists of the variable objects of the current execution environment (before entering the execution stage) and a series of active objects of the upper environment, which ensures the orderly access of the variables and functions that meet the access permissions of the current execution.

A clear understanding of scope chain can help us understand js many problems including closure problems, and so on. Let’s combine an example to understand scope chain.

var num = 30;

function test() {
    var a = 10;

    function innerTest() {
        var b = 20;

        return a + b
    }

    innerTest()
}

test()
Copy the code

In the example above, when the innerTest function is called, the innerTest function environment is entered. The global execution context and the test function execution context have entered the execution phase. The innerTest function execution context creates variable objects during the precompilation phase, so their active and variable objects are AO (global), AO (test), and VO (innerTest), respectively. The innerTest’s scope chain consists of variable objects in the current execution environment (before execution) and a series of active objects in the upper environment, as follows:

InnerTestEC = {VO: {b: undefined}, scopeChain: [VO(innerTest), AO(test), AO(global)], // This points to this: window }Copy the code

Here we can directly represent the scope chain with an array, and the active object or variable object of the scope chain can be directly understood as the scope.

The first item in the scope chain is always the current scope (variable object or active object in the current context);

2. The last item is always the global scope (the active object in the global context);

3. Scope chain ensures the orderly access of variables and functions. The search method is to search variables or functions from left to right along the scope chain.

Holdings closure

What is a closure? Think about it

Let’s look at a simple example

function foo() {
    var num = 20;

    function bar() {
        var result = num + 20;

        return result
    }

    bar()
}

foo()
Copy the code

Because there are many different understandings of closures, including some books I read (JS advanced programming), I will directly use the browser to parse, based on the browser closure to analyze the closure, as shown in the figure:

As you can see, Foo is the closure Google browser understands, so in terms of how browser standards define closures, I summarize three points:

1. Define new functions inside functions

2. The new function accesses the local variables of the outer function, that is, the active object properties of the outer function environment

3, new function execution, create the execution context of the new function, the outer function is the closure

4.2.4 Determine the direction of this

1. In the global environment, the this attribute of the variable object in the context of global execution points to window;

2. In the function environment, the “This” direction is flexible, which needs to be determined according to the execution environment and method. Typical examples are listed for analysis

Five, the summary

Because there is too much to cover, the third phase (the implementation phase) will be separated out next time. In addition, a new article is published for detailed analysis, mainly introducing the synchronous task execution and asynchronous task execution mechanism (Event Loop) in the JS execution stage.

Six, reference

Javascript you Don’t Know (Volume 1)

All kinds of benefits

1, byte push benefits

  • Reply “school admission” to get internal push code
  • Reply “Social recruitment” to get internal promotion
  • Reply “intern” to get internal push

There will be more benefits later

2. Learning materials welfare

Reply “Algorithm” to obtain algorithm learning materials

3. One question of the day

  • Q: Tell me more about the JS data type

  • 9. Doesn’t requestAnimationFrame smell good?

  • Q: What is your understanding of ES6 proxy?

  • Interviewer: What is the difference between “for in” and “for of”?

  • 6. How can Async/Await Async/Await Async?

  • How does VUE data binding work?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

  • 1. “How does an interview question trigger deep soul searching?”

Thank you for your support

1, if you like, you can “share, like, watch” three lian oh.

2, author nickname: SaucXS, songEagle, Songbao write code. A front-end engineer of Bytedance, an author who is working hard to grow, Star Sea, which has a promising future, will work in all departments of Bytedance.

3, long press the picture below, pay attention to “Songbao write code”, it is to obtain the development knowledge system construction, selected articles, project actual combat, laboratory, a daily interview question, advanced learning, thinking about career development, involving JavaScript, Node, Vue, React, browser, HTTP and other fields, I hope it can help you. We grow up together