Home  >  Article  >  Web Front-end  >  Detailed introduction to execution environment and scope in ES5 (code example)

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

不言
不言forward
2018-11-21 11:51:062216browse

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

对于有块级作用域的语言来说,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

以上代码中的函数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.com. If there is any infringement, please contact admin@php.cn delete