Home > Web Front-end > JS Tutorial > body text

Detailed explanation of execution environment and scope examples

零下一度
Release: 2017-06-26 15:21:52
Original
1442 people have browsed it

Execution context (execution context, sometimes also called "environment" for simplicity) is the most important concept in JavaScript. The execution environment defines the variables or other data that a function has access to, determining their respective behavior. 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 has no access to this object, the parser uses it behind the scenes when processing the data.

The global execution environment is the most peripheral execution environment. Depending on the host environment in which the ECMAScript implementation is located, the objects representing the execution environment are also different. In a Web browser, the global execution environment is considered the window object (discussed in detail in Chapter 7), so all global variables and functions are created as properties and methods of the window object. After all code in an execution environment has been executed, the environment is destroyed, and all variable and function definitions saved in it are also destroyed (the global execution environment is not executed until the application exits - such as closing the web page or browser) will be destroyed).

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 and returns control to the previous execution environment. The execution flow in ECMAScript programs is controlled by this convenient mechanism.

When code is executed in an environment, a scope chain of variable objects is created. The purpose of the scope chain is to ensure ordered access to all variables and functions that the execution environment has access to. The front end of the scope chain is always the variable object of the environment where the currently executing code is located. If the environment is a function, use its activation object as a variable object. The active object initially contains only one variable, the arguments object (this object does not exist in the global environment). The next variable object in the scope chain comes from the containing (external) environment, and the variable object after that comes from the next containing environment. In this way, it continues 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 always starts at the front of the scope chain and works backwards until the identifier is found (usually an error occurs if the identifier is not found).

Please look at the sample code below:

var color = "blue";
function changeColor() {
	if (color === "blue") {
		color = "red";
	} else {
		color = "blue";
	}
}
changeColor();
alert("Color is now " + color);
Copy after login

Run it

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's 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 the local scope can be used interchangeably with global variables in the local environment, as shown in the following example:

var color = "blue";
function changeColor() {
	var anotherColor = "red";
	function swapColors() {
		var tempColor = anotherColor;
		anotherColor = color;
		color = tempColor;
		// 这里可以访问color、anotherColor 和tempColor
	}
	// 这里可以访问color 和anotherColor,但不能访问tempColor
	swapColors();
}
// 这里只能访问color
changeColor();
Copy after login

以上代码共涉及3 个执行环境:全局环境、changeColor()的局部环境和swapColors()的局部环境。全局环境中有一个变量color 和一个函数changeColor()。changeColor()的局部环境中有一个名为anotherColor 的变量和一个名为swapColors()的函数,但它也可以访问全局环境中的变量color。swapColors()的局部环境中有一个变量tempColor,该变量只能在这个环境中访问到。

无论全局环境还是changeColor()的局部环境都无权访问tempColor。然而,在swapColors()内部则可以访问其他两个环境中的所有变量,因为那两个环境是它的父执行环境。图4-3 形象地展示了前面这个例子的作用域链。

图4-3 中的矩形表示特定的执行环境。其中,内部环境可以通过作用域链访问所有的外部环境,但外部环境不能访问内部环境中的任何变量和函数。这些环境之间的联系是线性、有次序的。每个环境都可以向上搜索作用域链,以查询变量和函数名;但任何环境都不能通过向下搜索作用域链而进入另一个执行环境。对于这个例子中的swapColors()而言,其作用域链中包含3 个对象:swapColors()的变量对象、changeColor()的变量对象和全局变量对象。swapColors()的局部环境开始时会先在自己的变量对象中搜索变量和函数名,如果搜索不到则再搜索上一级作用域链。changeColor()的作用域链中只包含两个对象:它自己的变量对象和全局变量对象。这也就是说,它不能访问swapColors()的环境。

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

4.2.1 延长作用域链

虽然执行环境的类型总共只有两种——全局和局部(函数),但还是有其他办法来延长作用域链。

这么说是因为有些语句可以在作用域链的前端临时增加一个变量对象,该变量对象会在代码执行后被移除。在两种情况下会发生这种现象。具体来说,就是当执行流进入下列任何一个语句时,作用域链就会得到加长:

  • try-catch 语句的catch 块;

  • with 语句。

这两个语句都会在作用域链的前端添加一个变量对象。对with 语句来说,会将指定的对象添加到作用域链中。对catch 语句来说,会创建一个新的变量对象,其中包含的是被抛出的错误对象的声明。

下面看一个例子。

function buildUrl() {
	var qs = "?debug=true";
	with(location) {
		var url = href + qs;
	}
	return url;
}
Copy after login

运行一下

在此,with 语句接收的是location 对象,因此其变量对象中就包含了location 对象的所有属性和方法,而这个变量对象被添加到了作用域链的前端。buildUrl()函数中定义了一个变量qs。当在with 语句中引用变量href 时(实际引用的是location.href),可以在当前执行环境的变量对象中找到。当引用变量qs 时,引用的则是在buildUrl()中定义的那个变量,而该变量位于函数环境的变量对象中。至于with 语句内部,则定义了一个名为url 的变量,因而url 就成了函数执行环境的一部分,所以可以作为函数的值被返回。

在IE8 及之前版本的JavaScript 实现中,存在一个与标准不一致的地方,即在catch 语句中捕获的错误对象会被添加到执行环境的变量对象,而不是catch 语句的变量对象中。换句话说,即使是在catch 块的外部也可以访问到错误对象。IE9 修复了这个问题。

4.2.2 没有块级作用域

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

if (true) {
    var color = "blue";
}
alert(color); //"blue"
Copy after login

这里是在一个if 语句中定义了变量color。如果是在C、C++或Java 中,color 会在if 语句执行完毕后被销毁。但在JavaScript 中,if 语句中的变量声明会将变量添加到当前的执行环境(在这里是全局环境)中。在使用for 语句时尤其要牢记这一差异,例如:

for (var i=0; i < 10; i++){
    doSomething(i);
}
alert(i); //10
Copy after login

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

1. 声明变量

使用var 声明的变量会自动被添加到最接近的环境中。在函数内部,最接近的环境就是函数的局部环境;在with 语句中,最接近的环境是函数环境。如果初始化变量时没有使用var 声明,该变量会自动被添加到全局环境。如下所示:

function add(num1, num2) {
    var sum = num1 + num2;
    return sum;
}
var result = add(10, 20); //30
alert(sum); //由于sum 不是有效的变量,因此会导致错误
Copy after login

运行一下

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

function add(num1, num2) {
    sum = num1 + num2;
    return sum;
}
var result = add(10, 20); //30
alert(sum); //30
Copy after login

运行一下

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

在编写JavaScript 代码的过程中,不声明而直接初始化变量是一个常见的错误做法,因为这样可能会导致意外。我们建议在初始化变量之前,一定要先声明,这样就可以避免类似问题。在严格模式下,初始化未经声明的变量会导致错误。

2. 查询标识符

当在某个环境中为了读取或写入而引用一个标识符时,必须通过搜索来确定该标识符实际代表什么。搜索过程从作用域链的前端开始,向上逐级查询与给定名字匹配的标识符。如果在局部环境中找到了该标识符,搜索过程停止,变量就绪。如果在局部环境中没有找到该变量名,则继续沿作用域链向上搜索。搜索过程将一直追溯到全局环境的变量对象。如果在全局环境中也没有找到这个标识符,则意味着该变量尚未声明。

通过下面这个示例,可以理解查询标识符的过程:

var color = "blue";
    function getColor(){
    return color;
}
alert(getColor()); //"blue"
Copy after login

运行一下

调用本例中的函数getColor()时会引用变量color。为了确定变量color 的值,将开始一个两步的搜索过程。首先,搜索getColor()的变量对象,查找其中是否包含一个名为color 的标识符。

在没有找到的情况下,搜索继续到下一个变量对象(全局环境的变量对象),然后在那里找到了名为color 的标识符。因为搜索到了定义这个变量的变量对象,搜索过程宣告结束。图4-4 形象地展示了上述搜索过程。

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

var color = "blue";
function getColor(){
    var color = "red";
    return color;
}
alert(getColor()); //"red"
Copy after login

运行一下

修改后的代码在getColor()函数中声明了一个名为color 的局部变量。调用函数时,该变量就会被声明。而当函数中的第二行代码执行时,意味着必须找到并返回变量color 的值。搜索过程首先从局部环境中开始,而且在这里发现了一个名为color 的变量,其值为"red"。因为变量已经找到了,所以搜索即行停止,return 语句就使用这个局部变量,并为函数会返回"red"。也就是说,任何位于局部变量color 的声明之后的代码,如果不使用window.color 都无法访问全局color变量。

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

The above is the detailed content of Detailed explanation of execution environment and scope examples. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!