gpt4 book ai didi

javascript - ES6 const 赋值中的意外行为

转载 作者:行者123 更新时间:2023-11-30 15:16:28 26 4
gpt4 key购买 nike

鉴于以下情况:

const foo = foo; // Uncaught ReferenceError: foo is not defined

尝试跟进:

const foo = 123; // Uncaught SyntaxError: Identifier 'foo' has already been declared

foo 从未设置,并且在 Chrome 和 Firefox 中都可以看到类似的行为。

这里发生了什么?

最佳答案

你在这里经历的是时间死区。变量 foo 已声明,但尚未初始化。事实上,您试图正确地初始化它,但是在 foo 可以设置为一个值之前,对该表达式的评估引发了异常。现在它永远未初始化 - 你只有一次机会。

这是一个已知问题。 From es-discuss (杰森·奥伦多夫):

I just realized this has an unfortunate implication for REPLs. Suppose you make this typo:

js> let x = Math.cso(a)    // oops, TypeError, should be Math.cos

Now x is irreparably hosed in your REPL. That seems bad.

I guess we can fix this by making the REPL bend the rules of the language. But this is rather hard to do for REPLs implemented in JS. Maybe the rules should just be a little more forgiving.

关于javascript - ES6 const 赋值中的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44388659/

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