JavaScript函数的作用域链是哈希表吗?

ps:作用域链是一个函数被创建的作用域中的对象的集合。
image.png
图取自《高性能JavaScript》
根据这张图以及考虑到JavaScript对象的数据结构是哈希表,所以我觉得作用域链也是一个哈希表,还请指教

阅读 2.3k
3 个回答

作用域链

这是 ES6 Spec 里对作用域(ES6 叫词法环境)的解释。

8.1 Lexical Environments

A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code. A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.

A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment.
词法环境由一个 环境记录表 和一个指向外部词法环境的引用(可能为null)构成。

这是一个链表结构。 lexicalEnv -> outer -> outer 最终指向 globalEnv 。

函数对象对作用域是怎么引用的?

Spec 9.2 章节也有介绍: 函数对象有一个内部槽(属性)[[Environment]], 指向函数创建时候的词法环境。当函数被运行的时候,这个环境就会被当作运行环境的外部环境。

image.png

综上,作用域链是链表形式,函数只引用了外一层的环境。

作用域链从访问的角度来看确实是一个集合,但不单是一个集合。
查找的时候向上查找,是有序的;由于嵌套的内外层会有覆盖,变量名也不单一,只是对访问者是单一的。
从访问的角度,确实可以把某个函数执行时可访问的所有变量放到一个哈希表里,但是这个哈希表不能完整描述这条作用域链的特征(链条长了之后读取时间变长,而哈希表理论上不应存在这样的差距)。
楼上说得对。

你是说函数执行的堆栈?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题