gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:43:49 30 4
gpt4 key购买 nike

我在玩弄新的 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 使用 block 作用域。与此范围界定有什么关系吗?

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

最佳答案

这是 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 提升非常严格。

我认为这是有道理的。

关于javascript - 未为立即调用的函数提升 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30478518/

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