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

标签 javascript ecmascript-6

我明白 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/

相关文章:

javascript - jQuery,如何在页面加载时禁用或启用带有复选框的 <select> 元素?

javascript - Twitter API 推文位置

javascript - 如何自动生成域和范围?有人知道为什么我的数据没有显示吗?

javascript - 为什么 Array.prototype.reduce() 不接受 Map 对象作为初始值?

javascript - Array.fill 重复相同的对象。为什么?

javascript - "Unterminated template literal"文字包含脚本标签时出现语法错误

javascript - 如何在 react 组件中为内部函数声明一个变量?

javascript - 无需编写多个 if else 语句即可验证多个变量

javascript - PhantomJS 加载页面的时间比 cURL 更多

ecmascript-6 - ES6数组理解不再有效吗?