什么叫死区时间_什么是时间死区?

I've heard that accessing let and const values before they are declared can cause a ReferenceError because of something called the temporal dead zone.

What is the temporal dead zone, how does it relate to scope and hoisting, and in what situations is it encountered?

解决方案

let and const have two broad differences from var:

Accessing a var before it is declared has the result undefined; accessing a let or const before it is declared throws ReferenceError:

console.log(aVar); // undefined

console.log(aLet); // causes ReferenceError: aLet is not defined

var aVar = 1;

let aLet = 2;

It appears from these examples that let declarations (and const, which works the same way) may not be hoisted, since aLet does not appear to exist before it is assigned a value.

That is not the case, however—let and const are hoisted (like var, class and function), but there is a period between entering scope and being declared where they cannot be accessed. This period is the temporal dead zone (TDZ).

The TDZ ends when aLet is declared, rather than assigned:

//console.log(aLet) // would throw ReferenceError

let aLet;

console.log(aLet); // undefined

aLet = 10;

console.log(aLet); // 10

This example shows that let is hoisted:

let x = 'outer value';

(function() {

// start TDZ for x

console.log(x);

let x = 'inner value'; // declaration ends TDZ for x

}());

Accessing x in the inner scope still causes a ReferenceError. If let were not hoisted, it would log outer value.

The TDZ is a good thing because it helps to highlight bugs—accessing a value before it has been declared is rarely intentional.

The TDZ also applies to default function arguments. Arguments are evaluated left to right, and each argument is in the TDZ until it is assigned:

// b is in TDZ until its value is assigned

function testDefaults(a=b, b) { }

testDefaults(undefined, 1); // throws ReferenceError because the evaluation of a reads b before it has been evaluated.

The TDZ is not enabled by default in the babel.js transpiler. Turn on "high compliance" mode to use it in the REPL. Supply the es6.spec.blockScoping flag to use it with the CLI or as a library.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值