search
HomeWeb Front-endJS TutorialDetailed introduction to execution environment and scope in ES5 (code example)

This article brings you a detailed introduction (code example) about the execution environment and scope in ES5. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface: I have been reading Javascript Advanced Programming in detail recently. For me, the Chinese version has touched upon many places in the book, so I will try to interpret it in detail using what I understand. If there are any mistakes or omissions, we will be very grateful for your pointing them out. Most of the content in this article is quoted from "JavaScript Advanced Programming, Third Edition"

Execution context

Execution context (execution context, for simplicity, sometimes also becomes Environment) is the most important concept in JavaScript.

The execution environment defines the permissions of variables or functions to access other data and determines their respective behaviors.

Each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in this object.

Although the code we write cannot access this object, the parser uses it behind the scenes when processing data.

The global execution environment is the most peripheral execution environment.

Depending on the host environment where ECMAScript is implemented, the objects representing the execution environment are also different.

In a web browser, the global execution environment is considered to be the window object, so all global variables and functions are created as properties and methods of the window object.

(the life cycle of variables), after all the code in an execution environment is executed, the environment is destroyed, and all variables and function definitions saved in it are also destroyed)

The global execution environment will not be destroyed until the application exits - such as closing the web page or browser.

Each function has its own execution environment. When the execution flow enters a function, the function's environment is pushed into an environment stack. After the function is executed, the stack pops its environment, returning control to the previous execution environment. The execution flow in ECMAScript programs is controlled by this convenient mechanism.

Scope chain

When code is executed in an environment, a scope chain of variable objects is created.
The purpose of the scope chain is to ensure orderly access to all variables and functions that have access to the execution environment.

The front end of the scope chain is always the variable object of the environment where the currently executed code is located. (It can also be understood as the "proximity principle").

If this environment is a function, use its activation object(activation object) as a variable object.

The active object in the function execution environment initially contains only one variable, the arguments object (this object does not exist in the global environment) as a variable object.

The next variable object in the scope chain comes from the containing (external) environment, and the next variable object comes from the next containing environment, and so on, continuing to the global execution environment.

The variable object of the global execution environment is always the last object in the scope chain.

Identifier resolution is the process of searching for identifiers level by level along the scope chain.
The search process always starts at the front of the scope chain and works backward step by step until the identifier is found (if the identifier is not found, an error will occur).

var color = "blue";

function changeColor() {
    if(color === "blue") {
        color = "red";
    } else {
        color = "blue";
    }
}

changeColor();

console.log("Color is now " + color); // "color is now red"

In this simple example, the scope chain of the function changeColor() contains two objects:

its own variable object (in which the arguments object is defined) and the global Environment variable object.

The variable color can be accessed inside the function because it can be found in this scope chain.

In addition, variables defined in a local scope can be used interchangeably with global variables in the local environment.

var color = "blue";

function changeColor() {
    var anotherColor = "red";

    function swapColors(){

        //这里可以访问color、anotherColor和tempColor
        var tempColor = anotherColor;
        anotherColor = color;
        color = tempColor;
    }

    //这里可以访问color和anotherColor,但不能访问tempColor
    swapColors();
}

//这里只能访问color
changeColor();

The above code involves 3 execution environments:

  • Global environment (window in a web browser)

  • Local environment of function changeColor()

  • Local local of function swapColors()

There is a variable color and a function changeColor in the global environment (). There is a variable called anotherColor and a function called swapColors() in the local environment of changeColor(), but it can also access the variable color in the global environment. There is a variable tempColor in the local environment of swapColors(), which can only be accessed in this environment.

Neither the global environment nor the local environment of changeColor() has access to tempColor.

However, inside swapColors(), you can access variables in the other two environments because those two environments are its parent execution environments.

      
 window, color, changeColor()
            |
    anotherColor, swapColors()
                    |
                tempColor

The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment.

The relationship between these environments is linear and sequential.

每个环境都可以向上搜索作用域链,以查询变量和函数名。但是,任何环境都不能通过向下搜索作用域链而进入另一个执行环境。

函数参数也被当做变量来对待,因此其访问规则与执行环境中的其他变量相同。

没有块级作用域(ES5中没有)

JavaScript没有块级作用域经常会导致理解上的困惑。
在其他类C的语言中,由花括号封闭的代码块都有自己的作用域(如果用ECMAScript的话来讲,就是它们自己的执行环境),因而支持根据条件来定义变量。

if(true) {
    var color = "blue";
}

console.log(color); //"blue"

这里是在有一个if语句中定义了变量color。
如果是在C、C++或Java中,color会在if语句执行完毕后被销毁。
但在JavaScript中,if语句中的变量声明会将变量添加当前的执行环境(在这里是全局环境window)中。

在使用for语句时尤其要牢记这一差异。

for(var i = 0; i <p>对于有块级作用域的语言来说,for语句初始化变量的表达式所定义的变量,只会存在于循坏的环境之中。而对于JavaScript来说,由for语句创建的变量i即使在for循环结束之后,也依旧会存在于循坏外部的执行环境中。</p><h3 id="声明变量">声明变量</h3><p><strong>使用var声明的变量会自动被添加到最接近的环境中,在函数内部,最接近的环境就是函数的局部环境。</strong></p><p>如果初始化变量时没有使用var声明,该变量会自动被添加到全局作用域。</p><pre class="brush:php;toolbar:false">function add(num1, num2) {
    var sum = num1 + num2;
    return sum;
}

var result = add(10,20); //30
console.log(sum); //sum is not defined

以上代码中的函数add()定义了一个名为sum的局部变量,该变量包含加法操作的结果。
虽然结果值从函数中返回了,但变量sum在函数外部是访问不到的。
如果省略这个例子中的var关键字,那么当add()执行完毕后,sum也将可以访问到。

function add(num1, num2) {
    sum = num1 + num2;
    return sum;
}

var result = add(10,20); // 30
console.log(sum); 30

在这个例子中的变量sum在被初始化赋值时没有使用var关键字。
于是,当调用完add()之后,添加到全局环境中的变量sum将继续存在。
即使函数已经执行完毕,后面的代码依旧可以访问它。

在编写JavaScript代码的过程中,不声明而直接初始化变量时一个常见的错误,这样会导致一些不可预估的意外。养成良好的习惯,在初始化变量之前,一定要先声明,这样就可以避免类似问题。在严格模式下,初始化未经声明的变量会导致错误。

2.查询标识符

当在某个环境中为了读取或写入而引用一个标识符时,必须通过搜索来确定该标识符实际代表什么。搜索过程从作用域链的前端开始,向上逐级查询与给定名字匹配的标识符。

如果在局部环境中找到了该标识符,搜索过程停止,变量就绪。

如果在局部环境中没有找到该变量,则继续沿作用域向上搜索。

搜索过程将一直追溯到全局环境的变量对象。

如果在全局环境中也没有找到这个标识符,则意味着该变量尚未声明。

var color = "blue";

function getColor() {
    return color;
}

console.log(getColor()); // "blue"

/*
window = {
    color,
    getColor = function() {
        return color;
    }
}
*/

调用本例中的函数getColor()时会引用变量color。

为了确定变量color的值,将开始一个两步的搜索过程。

  • 首先,在getColor()的局部环境中搜索变量对象,查找其中是否包含一个名为color的标识符。

  • 然后,没有找到,对不?那就到外面的环境中找,在全局作用域中找到名为color的标识符。

搜索到了定义这个变量的变量对象,搜索过程宣告结束。

在这个搜索过程中,如果存在一个局部的变量的定义,则搜索会自动停止(找到了,我就不找了),不再进入另一个变量对象。换句话说,如果局部环境中存在着同名标识符,就不会使用位于父环境中的标识符。

var color = "blue";

function getColor() {
    var color = "red";
    return color;
}

console.log(getColor()); //"red"

修改后的代码在getColor()函数中声明了一个名为color的局部变量。
调用函数时,该变量就会被声明。而当函数中的第二行代码执行时,意味着必须找到并返回变量color的值。
搜索过程,首先从局部环境中开始,而且在这里发现了一个名为color的变量,其值为“red”。
变量已经在函数的局部环境中找到了,所以搜索停止,return语句就使用这个局部变量,并为函数返回“red”。

如果不使用window.color都无法访问全局color变量。

变量查询也不是没有代价的。很明显,访问局部变量要比访问全局变量更快,因为不用向上搜索作用域链。JavaScript引擎在优化标识符查询方面做得不错,因此这个差别在将来恐怕可以忽略不记。

但是,我们还是要养成良好的编程习惯。虽说,这个差别可以忽略不记。

The above is the detailed content of Detailed introduction to execution environment and scope in ES5 (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.