Table of Contents
Execution context
Scope chain
没有块级作用域(ES5中没有)
声明变量
2.查询标识符
Home Web Front-end JS Tutorial Detailed introduction to execution environment and scope in ES5 (code example)

Detailed introduction to execution environment and scope in ES5 (code example)

Nov 21, 2018 am 11:51 AM
javascript

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

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();
Copy after login

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

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

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

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

for(var i = 0; i < 10; i++) {
    console.log(i); // 0,1,2,3,4,5,6,7,8,9
}

/*
//等价于
var i;

for(i = 0; i < 10; i++) {
    console.log(i);
}

*/

console.log(i); //10
Copy after login

对于有块级作用域的语言来说,for语句初始化变量的表达式所定义的变量,只会存在于循坏的环境之中。而对于JavaScript来说,由for语句创建的变量i即使在for循环结束之后,也依旧会存在于循坏外部的执行环境中。

声明变量

使用var声明的变量会自动被添加到最接近的环境中,在函数内部,最接近的环境就是函数的局部环境。

如果初始化变量时没有使用var声明,该变量会自动被添加到全局作用域。

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

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

以上代码中的函数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
Copy after login

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

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

2.查询标识符

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

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

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

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

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

var color = "blue";

function getColor() {
    return color;
}

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

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

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

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

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

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

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

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

var color = "blue";

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

console.log(getColor()); //"red"
Copy after login

修改后的代码在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 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).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles