前端 - 请教一下关于JavaScript的 执行环境 和 活动对象
阿神
阿神 2017-04-10 15:25:20
[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个活动对象吗?谢谢。

阿神
阿神

闭关修行中......

全部回复(2)
ringa_lee

谢谢,也就是说,只要调用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"
迷茫

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 中描述

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号