ES6中起吊的目的是什么? [英] What is the purpose of let hoisting in ES6?

查看:102
本文介绍了ES6中起吊的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白, let 将被提升到块的顶部,但在初始化之前访问它将抛出 ReferenceError 因为时间死区

I understand that let will be hoisted to top of the block, but accessing it before initializing will throw ReferenceErrordue being in to Temporal Dead Zone

例如:

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

但是,这样的代码片无误会运行:

But a snippet like this will run without error:

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

我的问题

在访问时会出现错误, let 的目的是什么?另外还要做的是$ TD code>还有TDZ,我知道什么时候会抛出 undefined 但是是因为TDZ吗? p>

What is purpose of let getting hoisted to top when it will throw an error on accessing? Also do var also suffer from TDZ,I know when it will throw undefined but is it because of TDZ?

推荐答案

文档说:


变量是在包含词汇环境为$ b $时创建的b实例化,但可能不会以任何方式访问,直到变量的
LexicalBinding被评估
。当LexicalBinding
与Initializer定义的变量在评估LexicalBinding时被分配给其Initializer的
AssignmentExpression的值,而不是当
创建变量时。如果let声明中的LexicalBinding不具有初始化器,则在评估LexicalBinding时,该变量赋值为undefined

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关键字


let允许您将范围有限的变量声明到
块,语句或表达式上用来。 这与
var关键字不同,var关键字定义了全局变量,或者局部到
整个函数,无论块范围如何。

您还可以查看Kyle Simpson的这篇文章:而对于 let

You can also check this article by Kyle Simpson: For and against let

这篇关于ES6中起吊的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆