gpt4 book ai didi

javascript - 为什么 catch 子句有自己的词法环境?

转载 作者:数据小太阳 更新时间:2023-10-29 06:12:27 27 4
gpt4 key购买 nike

考虑以下摘录 from ECMA-262 v5.1 (我最近在 this question 中看到):

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 WithStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.

我认为这意味着 catch 子句的主体将像函数一样提升自己的变量,但显然 that's not the case :

var a = 1;
try {
console.log(x); // ReferenceError
} catch(ex) {
console.log(a); // 1, not undefined
var a = 3;
}

有人知道为什么吗?另外,为什么 catch 子句需要自己的词法环境?

最佳答案

是的,catch 子句确实有它们自己的词法环境。查看什么happens when it is evaluated :它创建一个新的(从当前的派生)并将异常标识符绑定(bind)到它。执行 catch block 时,当前 Execution Context's LexicalEnvironment 切换到新的,而 VariableEnvironment("其环境记录保存由 VariableStatementsFunctionDeclarations 创建的绑定(bind)") 保持不变。

console.log(a); // undefined - declared from within the catch,
// but in the current VariableEnvironment
a = 1;
console.log(typeof ex); // undefined - no binding
try {
console.log(ex); // a ReferenceError in this LexicalEnvironment
} catch (ex) { // introducing the new LexicalEnvironment
console.log(ex); // …and it works here!
var a = 3; // variable declaration
}

有趣的事实:如果您尝试在 catch 子句中声明一个函数(尽管在 block 中语法无效,“函数声明语句”通常被接受),它的作用域将成为当前的 VariableEnvironment 因此它将无法访问异常:

try {throw "some"} catch(x) { function y(){console.log(x, typeof x);} y(); }
// throws a ReferenceError for x ^

(更新:在 ES6 中不再如此,其中 block 级函数声明在 block 范围内有效并关闭)

关于javascript - 为什么 catch 子句有自己的词法环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15034864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com