未为立即调用的函数提升 const 变量

const variable not hoisted for immediately invoked function

我在玩新的 ECMASCRIPT-6 const 关键字。我不理解关键字的一种特定行为。

假设我有两个函数

第一种情况

(function(){
  console.log(_t); 
  const _t=10;
})();

第二种情况

function t(){
  console.log(_y); 
  const _y=11;
}
t();

对于第一种情况输出是(不明白为什么)

ReferenceError: can't access lexical declaration `_t' before initialization

对于第二种情况,输出是(很好)

undefined

第二种情况的输出符合预期,但我不明白为什么第一种情况的结果会抛出错误。从报错可以推断变量没有被提升。但为什么?我发现 here const 使用 块作用域 。与此范围界定有什么关系吗?

我正在使用 Firefox Developer Version 控制台进行 运行 测试。

当我在 Firefox (38.0.1) 中尝试时,我得到了相同的错误消息;它无法在初始化之前访问它。这是有道理的,因为唯一的区别是有一个函数表达式和一个函数声明。

常量标识符实际上被提升了,这就是为什么你会得到它在初始化之前无法访问的错误。

在这种情况下,块作用域和函数作用域是相同的,因为函数代码块是您仅有的块。

如果添加代码块,使常量在使用时超出范围,您将收到错误消息 "ReferenceError: _y is not defined":

function t(){
  {
    const _y = 11;
  }
  console.log(_y); // _y is out of scope
}
t();

这是 here

中提到的 Firefox 相关问题

Firefox 特定说明

The const declaration has been implemented in Firefox long before const appeared in the ECMAScript 6 specification. For const ES6 compliance see bug 950547 and bug 611388.

Starting with Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33):

{const a=1};a now throws a ReferenceError and does not return 1 anymore due to block-scoping. const a; now throws a SyntaxError ("missing = in const declaration"): An initializer is required. const a = 1; a = 2; now also throws a SyntaxError ("invalid assignment to const a").

我也发现了一些东西here

我认为 Firefox 引擎对 const 提升非常严格。

我认为这是有道理的。