了解let与var提升 [英] Understanding let vs. var hoisting

查看:136
本文介绍了了解let与var提升的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 let vs. var 我了解到,主要的区别是让变量的范围最近的街区,并没有悬挂。还可以让变量重新分配,但不能在同一范围内重新声明。为什么这段代码返回未定义错误?

With let vs. var I've learned that the major difference is that let variables are scoped to the nearest block and are not hoisted. Also let variables can be reassigned but cannot be redeclared within the same scope. Why then does this code return a "not defined" error?

let x = 10;
if (true) {
    console.log(x);
    let x = 11;
}

返回:

Uncaught ReferenceError: x is not defined(…)

let x = 10;
if (true) {
    console.log(x);
}

日志 10 一个错误?

推荐答案

var let 是:

var 被挂起到包裹 function block。

var is hoisted to the wrapping function block.

let 被提升到包装 {}

第二个代码示例与第一个代码示例没有相同的引用冲突,因为您声明 x 之前引用它在以下如果块。

The second code sample doesn't have the same reference conflict as the first because you're declaring x prior to referencing it in the following if block.

编辑要解决Pointy在下面的评论:

EDIT To address Pointy's comment below:

您正在体验 ReferenceError 由于时间死区

如果引用由 let 在定义之前,您将收到此错误。

If you reference a variable defined by let within the same block before it is defined you will receive this error.


从MDN let 文档



在ECMAScript 2015让我们把变量提升到块的顶部。但是,在变量声明之前引用块中的变量会导致ReferenceError。该变量处于从块开始到处理声明之前的暂时死区。

From MDN let Docs

In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

function do_something(){
console.log(foo); // ReferenceError
let foo = 2;
}

这篇关于了解let与var提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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