Table of Contents
Creation phase
Execution phase
Creation process of variable object (VO)
Compilation phase
Home Web Front-end JS Tutorial How JavaScript works

How JavaScript works

Jun 06, 2018 pm 02:56 PM
javascript Operating principle

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, if it encounters < ;script>xxx tag is to enter a global execution environment

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

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

Multiple execution contexts may be generated in a piece of JS code , 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

  • global execution context The stack will only pop up 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 the execution is completed, the stack is popped immediately, and then control is handed back to the next execution context.

  • The function will only be called each time it is called. Create an execution context for it, which was not available when the function was 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 phase mainly completes three events, 1. Create variable object 2. Establish scope chain 3. Determine this point

Execution phase

This phase mainly completes variable assignment, function calling, and others Operation

Creation process of variable object (VO)

  • 1. Create and initialize the arguments object according to the function parameters, and add attributes "0", "1 to the arguments object ", "2", "3" and other attributes, their 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);
Copy after login

Compilation phase

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

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
Copy after login

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

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

Execution phase

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

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, which context fn_EC also has two phases

They 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:

Use Native in React to implement the image viewing component

Use vue-cli combined with Element-ui in cropper. Encapsulate vue based on js to implement the image cropping component function

Realize a series of functions such as local preview, cropping, compression and upload of images in vue.js

The above is the detailed content of How JavaScript works. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

In-depth understanding of the working principle and main functions of the Struts2 framework In-depth understanding of the working principle and main functions of the Struts2 framework Jan 05, 2024 am 08:25 AM

To understand the operating principles and core features of the Struts2 framework, specific code examples are required. Struts2 is an open source web application framework based on Java. It is a subsequent version of the Struts framework. It provides an MVC (Model-View-Controller) architecture for Develop maintainable and scalable web applications. It is very important for developers to understand the operating principle and core features of Struts2. 1. The operating principle of Struts2 Struts2 is based on the MVC architecture.

See all articles