gpt4 book ai didi

javascript - ES6 中 let 提升的目的是什么?

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

我明白 let将被提升到 block 的顶部,但在初始化之前访问它会抛出 ReferenceError由于在 Temporal Dead Zone

例如:

console.log(x);   // Will throw Reference Error
let x = 'some value';

但是像这样的代码片段将运行而不会出错:

foo(); // alerts foo;
function foo(){ // foo will be hoisted
alert("foo");
}

我的问题

let 的目的是什么?当它会在访问时抛出错误时被提升到顶部?也做 var也遭受TDZ,我知道它什么时候会抛出undefined但这是因为 TDZ 吗?

最佳答案

documentation说:

The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

还有 var keyword :

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

您还可以查看 Kyle Simpson 的这篇文章:For and against let

关于javascript - ES6 中 let 提升的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597969/

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