search
HomeWeb Front-endJS TutorialDetailed explanation of execution context usage in pages

This time I will bring you a detailed explanation of the use of execution context in the page. What are the precautions of the execution context in the page. The following is a practical case, let's take a look.

When JavaScript code executes a piece of executable code, the corresponding execution context will be created and the context will be pushed into the context stack.

Context contains the following 3 important attributes:

name -
Variable object (VO, variable object) Variables, functions, and parameters defined by the current function
Scope chain The scope chain formed when the source code is defined
this

Context is an abstract concept. For ease of understanding, we assume that the context is an object and contains three attributes: VO, Scope, and this:

function foo (c) {
  let a = 1
  let b = function () {}
}
// foo函数的上下文
fooContext = {
        VO: {
            arguments: { // 实参
              c: undefind,
              length: 0
            },
            a: 1, // 变量
            b: reference to function (){} // 函数
        },
        Scope: [VO, globalContext.VO], // 作用域链
        this: undefind // 非严格模式下为 this
    }

So the context is the environment when the function is running or the dependent resource. A collection that determines which variables and functions can be obtained when the function is run.

Execution context (EC): If the function is in the executing state, the context of the function is called the execution context. At the same time, if the function is in the non-executing state, it is the (ordinary) context. So execution context is just a different state of context, essentially there is no difference between them.

Context stack

The context stack is also called the execution stack (ECS). The javascript parser in the browser itself is single-threaded, that is, it can only process one context and corresponding code segment at the same time. , so the JavaScript parsing engine uses the context stack to manage the context. All contexts will be saved in the context stack queue after they are created. The bottom of the stack is the global context, and the top of the stack is the currently executing context.

Detailed explanation of execution context usage in pages

A context is an execution unit, and JavaScript manages execution units in a stack. When the page is initialized, the global context will first be pushed at the bottom of the stack, and then when the executable function is executed according to the rules, the context of the function will be pushed into the Context stack. The pushed context contains the function running The resources (variable objects, scope chains, this) required when running, these resources are provided to expression when the function is run.

The execution context can be understood as the environment when the function is running. At the same time, execution context is also an invisible concept.

There are 3 running environments in javascript:

  • Global environment: window in the browser, in the node environment global, when the page is initialized, the global context will be pushed into the context stack;

  • Function environment: When the function is called and executed, the resources of the function will be collected, the context will be created and pushed Enter the context stack;

  • eval environment, deprecated

A running environment will correspond to a context. The context at the top of the stack will automatically pop off the stack after it is executed, and then go down until all contexts have finished running. Finally, the global context is destroyed when the browser is closed. For easier understanding, let’s give an example:

let i = 0
function foo () {
    i++
    console.log(i, 'foo')
}
function too () {
    i++
    console.log(i, 'too')
    foo()
}
function don () {
    i++
    console.log(i, 'don')
    too()
}
don()
 // 1 "don"
 // 2 "too"
 // 3 "foo"

The logic of the above code is to execute don() first, then too(), foo(). The context stack when executing foo() is like this:

Detailed explanation of execution context usage in pages

We assume that the context stack is an array: ECStack:

ECStack = []
## After #javascript is loaded, the first thing to parse and execute is the global code, so the global context will be pushed to the context stack during initialization, which we use

globalContext to represent.

ECStack = [
    globalContext
]
The global scope will exist throughout the code running phase until the page is closed.

ECStack will be empty, and globalContext will be destroyed.

When the global context is created, operations such as variable promotion and variable object generation are performed, and then the executable code (functions, expressions) in the current context will be executed. When a function call is encountered, the context of the function will be

push in the context stack.

function foo () {
    console.log('foo')
}
function too () {
    console.log('too')
    foo()
}
function don () {
    too()
}
don()
The execution logic can be understood as:

  1. Execute to don(), parse the internal code of the don function

  2. generate don The context of the function (vo, Scope chain, this)

  3. Push the context of don to ECStack

  4. Execute the expression inside the don function body

  5. Execute too()

  6. Generate the context of too function (vo, Scope chain, this)

  7. Push the context of too into ECStack

  8. ...

The javascript parser continues to recurse until the foo function is executed... The foo function context is popped... then backtracks to the

globalContext context... waits... and executes the callback function when the event's callback function is activated. (This involves the execution mechanism and event loop of javascript, please pay attention to subsequent articles ^_^)

执行逻辑的伪代码如下:

// 伪代码
// don()
ECStack.push(<don> functionContext);
// 在don中调用了too, push too的上下文到上下文栈里
ECStack.push(<fun2> functionContext);
// 在too中调用了foo, push foo的上下文到上下文栈里
ECStack.push(<fun3> functionContext);
// foo执行完毕, 弹出上下文
ECStack.pop();
// too执行完毕, 弹出上下文
ECStack.pop();
// don执行完毕, 弹出上下文
ECStack.pop();
// 非全局上下文执行完毕被弹出后会一直停留在全局上下文里,直至页面关闭</fun3></fun2></don>
需要注意的是,上下文与作用域(scope)是不同的概念。上下文是一个运行时概念,浏览器运行后执行 js 代码,将不同的上下文加入上下文栈中,顶层的上下文对应的代码块执行完后又将该上下文销毁。 而作用域是一个静态概念,根据所在代码片段的位置及词法关系确立的,不管浏览器运行与否,源代码的作用域关系、变量的访问权限依然不变。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

前端测试金字塔使用步骤详解

怎样处理MySQL数据库拒绝访问

The above is the detailed content of Detailed explanation of execution context usage in pages. 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
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.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool