如何在词汇环境中管理块范围? [英] How is block scope managed in the lexical environment?
问题描述
如果我使用 var
在函数中声明变量,那么该变量的插槽将添加到 LexicalEnvironment
由该函数定义。
If I declare a variable in a function using var
then a slot for that variable is added to the LexicalEnvironment
defined by that function.
function() {
var foo;
}
在上面的代码中 LexicalEnvironment $ c与该函数关联的$ c>包含一个带有键
foo
的插槽,以及值 undefined
。
In the above code the LexicalEnvironment
associated with the function contains a slot with a key foo
and a value of undefined
.
如果我使用块范围声明,周围的 LexicalEnvironment
如何受到影响?
If I use a block-scoped declaration, how is the surrounding LexicalEnvironment
affected?
function() {
{
let foo; // How does this affect the LexicalEnvironment?
}
}
推荐答案
function() {
var foo;
}
如你所述, foo
在中可用LexicalEnvironment
对该函数中的所有内部函数都是全局的。
As you mentioned, foo
is available in the LexicalEnvironment
is global to all inner functions within that function.
但是
function() {
{
let foo; // How does this affect the LexicalEnviroinment?
}
}
这里 foo
仅对该块是本地的。它不会在那个街区外面看到。
Here foo
is local to that block alone. It won't be visible outside that block.
它如何影响 LexicalEnvironment
?
如果您在该块内的任何地方引用 foo
,则本地 let foo
将覆盖全局 var foo
。
If you are referencing, foo
anywhere inside that block, the local let foo
will override the global var foo
which you've defined in that function.
关于ES6,
With respect to ES6,
function example(x) {
console.log(y); // ReferenceError: y is not defined
if (x) {
let y = 5;
}
}
用声明的变量let
语句被创建为当前执行上下文的词法环境而不是变量环境的绑定。 ES6中块语句规范的更改意味着每个块都有自己的词法环境。在上面的示例中,在计算块(if语句的主体)时会创建一个新的词法环境。当评估let语句时,绑定被添加到这个词法环境中,并且不能从外部词汇环境(函数声明本身)环境中获取。
Variables declared with a let
statement are created as bindings on the lexical environment, rather than the variable environment, of the current execution context. A change to the specification of block statements in ES6 means that each block has its own lexical environment. In the above example, a new lexical environment is created when the block (the body of the if statement) is evaluated. When the let statement is evaluated a binding is added to this lexical environment and is innaccessible from the outer lexical environment (that of the function declaration itself).
< a href =http://globaldev.co.uk/2013/09/es6-part-2/ =nofollow>推荐
Refer
这篇关于如何在词汇环境中管理块范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!