我明白 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 吗?
最佳答案
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/