4 执行环境

1 什么是执行环境?

执行环境定义了变量或函数有权访问的其他数据。

Each execution context has an associated variable object upon which all of its defined variables and functions exist.

The global execution context is the outermost one.

When an execution context has executed all of its code, it is destroyed, taking with it all of the variables and functions defined within it.

执行环境有三种情况:

全局,

函数,

对象。

2 一个例子:深刻理解执行环境

function sayName(){
    alert(name);
}
var name = "A";
sayName();

当程序执行到var name = “A”这行代码时,这时环境栈中只有一个执行环境,全局环境(对应window对象)。如下图:

继续,当程序执行到sayName ()中的代码时,这时有二个执行环境,全局环境(对应window对象),全局环境的variable object中存在name变量 和 sayName函数。sayName环境,sayName环境的variable object中只有一个arguments对象。

这时,sayName环境被推入到了环境栈中。

再继续,当程序执行完sayName()这行代码时,这时sayName环境被摧毁,又只剩下全局环境。如下图:

原文地址:https://www.cnblogs.com/lijy/p/6526586.html