我正在阅读一篇文章,试图了解词法作用域以及VariableEnvironment 的工作原理。我理解代码并且它是有道理的,但我没有得到前面的解释,这让我有点担心。有人可以为我重新措辞以确保我完全理解这一点吗?
Every function gets a [[scope]] property, and when the function is invoked the value of the scope property is assigned to the outer lexical environment reference (or outerLex) property of its VariableEnvironment. (ES 5 10.4.3.5-7) In this way, each VariableEnvironment inherits from the VariableEnvironment of its lexical parent. This scope chaining runs the length of the lexical hierarchy starting from the global object.
//VariableEnvironment: {x: undefined, etc.};
var x = "global";
//VariableEnvironment: {x: "global", etc.};
function outer() {
//VariableEnvironment: {y: undefined, outerLex: {x: "global", etc.}};
var y = "outer";
//VariableEnvironment: {y: "outer", outerLex: {x: "global", etc.}};
function inner() {
//VariableEnvironment: {x: undefined, outerLex: {y: "outer", outerLex: {x:"global", etc.}};
var x = "inner";
//VariableEnvironment: {x: "inner", outerLex: {y: "outer", outerLex: {x:"global", etc.}};
}
}
还有一种方法可以访问函数的 VariableEnvironment 吗? 函数.VariableEnvironment?或者函数.[[scope]]?两者似乎都不起作用。
更新
相关文章是here
最佳答案
首先要了解的是 lexical 这个词在这种情况下的含义。 “词法”范围是可以通过在源代码中定义的上下文中查看函数,在函数内的声明(var
,let
、const
、function
),以及在向外到全局范围的封闭函数层中的声明。这是一个仅查找花括号和周围的 function
声明或表达式的过程。
然后,该描述只是一种正式的说法,即通过查找在本地范围内定义的符号来解析符号引用,然后在每个连续的“更全局”范围内,一直到实际的全局范围。 (请注意,在 Node 中,情况略有不同,因为实际的全局作用域并不直接属于词法作用域链的一部分。)
我认为“词法作用域”也被称为“静态作用域”,这是有道理的,因为它意味着作用域规则在每个函数的创建点(并且在 ES2015 中,每个 block ,用于 let
)。特别是,作用域不是动态的 - 关于函数何时何地被调用的规则不涉及任何内容。
关于javascript - 措辞不佳的 JavaScript 词法作用域示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972136/