在 Javascript 中,何时创建新范围?我知道的两种情况是:
请注意,任何新 block (在 if-then-else、循环或无其他原因只是开始一个 block )都不会创建新范围。
除了上述两种情况之外,是否还有第三种情况会创建新的范围?谢谢。
最佳答案
是的,在第三种情况下,作用域链被扩充(除了 Shog9 提到的 let
mozilla-extension),当 catch
block 被评估:
The production Catch : catch (Identifier ) Block is evaluated as follows:
Let C be the parameter that has been passed to this production.
Create a new object as if by the expression new Object().
Create a property in the object Result(2). The property's name is Identifier, valueisC. value, and attributes are { DontDelete }.
Add Result(2) to the front of the scope chain.
Evaluate Block.
Remove Result(2) from the front of the scope chain.
Return Result(5).
所以基本上,创建了一个新对象,其中一个名为 Identifier 的属性传递给
catch
,这个新对象被添加到作用域链中,因此我们可以在 catch
中使用该标识符堵塞。try {
throw "error";
} catch (identifier) {
// `identifier` accessible here..
}
但请记住,它只是暂时扩大了当前范围,以引入
catch
标识符,在内部声明的任何变量都将被简单地提升到其封闭函数的顶部。
关于javascript - 在 Javascript 中,何时创建新范围? (使用新功能并在 "with"语句中)只有这两种情况吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2730858/