请教一下关于JavaScript的 执行环境 和 活动对象


在下是一个js初学者,语文学的很抱歉,理解能力也有点渣...
最近学习了关于 执行环境 活动对象 的知识,懂了一些,但还是有些疑问。
关于执行环境的问题
书上说:
《JS高程》3版中说:“ 每个函数都有自己的执行环境 ”。“ 每个执行环境都有一个与之关联的变量对象 (variable object)。”

我有一个函数test


 function test (a) { alert(a); }

我调用test多次


 test(1) //弹出1
test(2) //弹出2
test(3) //弹出3

“每个 函数 都有 自己的执行环境”,那test这个函数,是说无论执行多少次,都只有 1个执行环境 1个活动对象 吗?谢谢。

web前端开发 JavaScript

Hawking 8 years, 10 months ago

ECMA大法好

http://www.ecma-international.org/ecma-262/5.1/#sec-10.3

A new execution context is created whenever control is transferred from the executable code associated with the currently running execution context to executable code that is not associated with that execution context.

在例子中每次执行test,当前执行代码都从“global”转移到test函数内部,因此会创建新的execution context,对应的过程在 http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.1 中描述

msz006 answered 8 years, 10 months ago

谢谢,也就是说,只要调用test这个函数,就会创建1个新的执行环境和1个新的活动对象。调用多少次,创建多少执行环境和活动对象,是这样理解吗?

这样理解是对的的。特别是在闭包中,这种概念可以体现出来,如下代码:


 function test(v) {
    var value = v;
    var setValue = function (newValue) {
      value = newValue;
    };
    var getValue = function () {
      return value;
    };

  return {
    "setValue": setValue,
    "getValue": getValue
  };

}

var a = test("a");
var b = test("b");
console.log(a.getValue());   //"a"
console.log(b.getValue());   //"b"

Yumeko answered 8 years, 10 months ago

Your Answer