search
HomeWeb Front-endJS TutorialDetailed analysis and answers to the principles of JavaScript operation

This article provides you with a detailed theoretical analysis of the operating principles of JavaScript and sharing of knowledge points. If you are interested in this, please learn it.

JavaScript is an object-based dynamic, weakly typed scripting language (hereinafter referred to as JS). It is an interpreted language. It is different from other programming languages, such as Java/C and other compiled languages. These languages Before the code is executed, the entire code will be compiled and first compiled into bytecode (machine code). Then execute. JS does not do this. JS does not need to be compiled into intermediate code, but can be run directly in the browser. The JS running process can be divided into two stages, compilation and execution. (Please refer to the book JS You Don’t Know), when the JS controller switches to a piece of executable code (this executable code is generated during the compilation phase), the corresponding Execution Context (EC for short). Execution context can be understood as the execution environment (execution context can only be created by the JS interpreter and can only be used by the JS interpreter. Users cannot operate the 'object').

The execution environment in JS is divided into three categories:

  • Global environment: When the JS engine enters a code block, such as When you encounter the <script>xxx</script> tag, you enter a global execution environment

  • Function environment: When a function is called, a function execution is formed inside the function Environment

  • eval(): Execute the string as JS code alone. It is not recommended to use

. Multiple errors may occur in a piece of JS code. An execution context. In JS, a data structure such as a stack is used to manage the execution context. The characteristics of the stack are "first in, last out, last in, first out". This kind of stack is called a function call stack.

Characteristics of execution context

  • The bottom of the stack is always the global execution context, and there is only one

  • The global execution context will only pop up the stack when the browser is closed

  • There is no limit to the number of other execution contexts

  • The top of the stack is always The current active execution context, the rest are in a waiting state, once execution is completed, the stack is popped immediately, and then control is handed back to the next execution context

  • The function is only called every time , an execution context will be created for it, which does not exist when the function is declared.

The execution context can be vividly understood as an ordinary JS object. The life cycle of an execution context roughly includes two phases:

Creation phase

This stage mainly completes three events, 1. Create variable object 2. Establish scope chain 3. Determine this point

Execution stage

This stage Mainly completes variable assignment, function calling, and other operations

The creation process of variable objects (VO)

  • 1. According to the function parameters, create and initialize the arguments object and give arguments The object adds attributes such as "0", "1", "2", and "3", whose initial value is undefined, and the arguments.length value is set to the actual number of parameters passed in.

  • 2. Find the function function declaration and add attributes to the variable object. The attribute name is the function name, and the attribute value is the reference value of the function. If there is already one with the same name, it will be overwritten directly

  • 3. Search for var variable declaration (when searching for a variable, the parameters of the function will be equivalent to the var declaration, so the same attribute as the parameter name will also be added to the VO, and the initial value will also be added. undefined), add an attribute to the variable object. The attribute name is the variable name and the attribute value is undefined. If an identifier with the same name already exists, it will not be processed.

If there is an identifier with the same name (function, variable ), the function can overwrite the variable, and the function has a higher priority than the variable

Variable object (OV) and activation object (AO) are the same thing, two names at different times. It is called the variable object during the creation period and the activation object during the execution period.

Take the following code as an example

var g_name="tom";
var g_age=20;
function g_fn(num){
 var l_name="kity";
 var l_age=18;
 function l_fn(){
  console.log(g_name + &#39;===&#39; + l_name + &#39;===&#39; + num);
 }
}
g_fn(10);

Compilation phase

When the JS controller switches to this piece of code, an execution context will be created. G_EC

The structure of the execution context is roughly as follows:

G_EC = {
 VO   : {},
 Scope_chain : [],
 this  : {}
}

/* VO的结构大概 */
VO = {
 g_name : undefined,
 g_age : undefined,
 g_fn : <函数在内存中引用值>
}

/* Scope_chain的大概结构如下 */
Scope_chain = [ G_EC.VO ] // 数组中第一个元素是当前执行上下文的VO,第二个是父执行上下文的VO,最后一个是全局执行上下文的VO,在执行阶段,会沿着这个作用域链一个一个的查找标识符,如果查到则返回,否知一直查找到全局执行上下文的VO

/* this */
this = undefined // 此时this的值是undefined

Once the execution context is created, it is immediately pushed into the function call stack. At this time, the interpreter will quietly do one thing, which is to add an internal attribute [[scope]] to the function in the current VO. Properties point to the scope chain above.

g_fn.scope = [ global_EC.VO ] // 该scope属性只能被JS解释器所使用,用户无法使用

Execution phase

The code is executed line by line. When an expression is encountered, it will be searched in the current scope chain. If the VO object is found, it will be returned. If it is not found, it will continue to search for the next VO object until the global VO object is terminated.

This stage can include variable assignment, function call and other operations. When the interpreter encounters g_fn(), it knows that this is a function call, and then immediately creates a function execution context for it, fn_EC. , the context fn_EC also has two phases

, which are the creation phase and the execution phase.

In the creation phase, for the function execution context, when creating a variable object, an additional arguments object will be created, and then attributes will be added to the arguments object: "0", "1", "2" whose initial value is undefined,

  • Find function function declaration

  • Find var variable declaration

The above is what I compiled for everyone , I hope it will be helpful to everyone in the future.

Related articles:

p5.jsImplementing golden spiral animation

Event delegation in JS Detailed explanation of usage

Vue.js Detailed explanation of usage of computed and methods

The above is the detailed content of Detailed analysis and answers to the principles of JavaScript operation. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function