Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does the JavaScript engine execute JS code

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "JavaScript engine how to execute JS code", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "how the JavaScript engine executes JS code" this article.

The operation of JS code

We know that js is a weakly typed language, and variable types are determined at run time. When executing js code, js engine also carries out lexical analysis, syntax analysis, semantic analysis and other processing from top to bottom, and generates AST (Abstract Syntax Tree) after code parsing is completed, and finally generates machine code that can be executed by CPU according to AST and executes.

In addition, the JS engine performs other processing when executing code, such as two phases in V8:

Compilation phase: this phase creates the execution context, including creating the variable object (VO) (which is initialized to undefined at this time), establishing the scope chain, determining the this pointing, and so on. Each time you enter a different operating environment. V8 creates a new execution context.

Execution phase: pushes the execution context created during the compilation phase into the call stack and becomes the running execution context. After the code is executed, it is popped off the call stack. (there is a VO-AO process: when JavaScript assigns a value to a variable, the variable is used, and the variable object is converted to the active object, and the converted active object can be accessed.)

This leads to two concepts: "execution context" and "scope chain".

JavaScript execution context

We know from the above that when js code executes a piece of executable code, a corresponding execution context is created.

First of all, there is a concept of executable code in js: "execution environment"-- global environment, functional environment, and eval.

Second, for each execution context, there are three important attributes:

Variable object (that is, "VO")

Domain chain

This

Let's take a look at two pieces of code:

Var scope= "global scope"; function checkscope () {var scope= "local scope"; function f () {return scope;} return f ();} checkscope (); var scope= "global scope"; function checkscope () {var scope= "local scope"; function f () {return scope;} return f;} checkscope () ()

What do they print?

Why? The answer is that their execution context stacks are different!

What is the execution context stack?

When executable code is executed, preparations are made in advance, and the "preparatory work" here is professionally referred to as "execution context". But with the increase of executable code such as functions, how do you manage so many execution contexts? So the JS engine created the concept of the execution context stack.

We can use arrays to simulate its behavior (there is always a global execution context globalContext at the bottom of the stack)

We define an EStack, first of all

EStack= [globalContext]

Then simulate the first piece of code:

EStack.push (functionContext); EStack.push (functionContext); EStack.pop (); EStack.pop ()

And the second piece of code looks like this:

EStack.push (functionContext); EStack.pop (); EStack.push (functionContext); EStack.pop ()

To investigate the reason, you may need to study the concept of "closure" first!

By the way, how to "save data for a long time" in "modularization at the front end"?

Cache? No, no. Closure!

JavaScript scope and scope chain

First of all, scope refers to the area in the program that defines variables. The scope specifies how to find the variable, that is, determines the currently executing code's access to the variable.

There are two kinds of scope: static scope and dynamic scope.

The static scope adopted by JS is also called "lexical scope". The scope of a function is determined when the function is defined.

From the above, the variables in the lexical scope will produce a definite scope in the compilation process. This scope is the "current execution context". After ES5, we use "lexical context" instead of scope to describe the execution context. The lexical environment consists of two members:

Self lexical environment record: used to record variable objects in one's own lexical environment

External lexical context references: used to record references that exist in the outer lexical environment

Let's still look at an example:

Var value=1;function foo () {console.log (value);} function bar () {var value=2; foo ();} bar ()

Looking back at the above definition, what should be printed?

Let's analyze the implementation process:

To execute the foo () function, first look inside the foo function to see if there is a local variable value. If not, according to the location of the definition, look for the code of the upper layer, namely value=1. So the result will print 1.

Of course, it is not so simple to sum up, you can analyze it from the perspective of execution context.

Establish a domain chain

Above we talked about the two components of lexical environment (scope). Combined with the execution context, it is not difficult to find that through the citation of the external lexical environment, the scope can be expanded layer by layer along the stack to establish a chain structure extending from the current environment.

Let's look at another example:

Function foo () {console.dir (bar); var axi1; function bar () {axi2;}} console.dir (foo); foo ()

By static scope, the global function foo creates a [[scope]] attribute of its own object.

Foo [[scope]] = [globalContext]

When we execute foo (), we also enter the definition period and execution period of the foo function. During the definition period of the foo function, the [[scope]] of the function bar will contain the built-in scope of the global built-in scope and foo

Bar [[scope]] = [fooContext,globalContext]

This proves the point: "JS creates a scope chain of variable objects through external lexical context references, thus ensuring orderly access to variables and functions that the execution environment has access to."

Let's go back to the question in the execution context. We talked about how they were different earlier, and here's why they printed "local scope" in the same way: the same sentence, "JS uses lexical scope, and the scope of the function depends on where the function is created"-- the execution of the JS function uses the scope chain, which is created when the function is defined. The nested function f () is defined in this scope chain, where the variable scope must refer to a local variable, and this binding is still valid when and where f () is executed.

Variable query based on scope chain

When a variable cannot be found in its own lexical context record, it can look for the outer layer according to the external lexical context reference until the outermost lexical environment is referenced as null.

Similar to this is "prototype chain-based lookup in objects":

Prototype: every JS object (except null) is associated with another object when it is created, which is what we call a prototype. Each object "inherits" the property from the prototype.

When reading the properties of an instance, if it cannot be found, it will look for the properties in the prototype associated with the object. If it cannot be found, it will find the prototype of the prototype until the top level (_ _ proto__ is null)

The difference between them is also obvious: prototype chains establish links inherited by objects through the prototype property, while scope chains refer to closures in which internal functions can access external functions. Whether directly or indirectly, the scope chains of all functions are eventually linked to the global context.

The above is all the content of the article "how the JavaScript engine executes JS code". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report