为什么这段代码不会导致ReferenceError? [英] Why does this code not result in a ReferenceError?

查看:102
本文介绍了为什么这段代码不会导致ReferenceError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if(true) {
  tmp = 'abc';
  console.log(tmp);//which should throw referenceError but not

  let tmp;
  console.log(tmp);

  tmp = 123;
  console.log(tmp);
}

此代码产生

abc
undefined
123

为什么第一个console.log(tmp)没有抛出错误?



为什么它应抛出referenceError

Why does the first console.log(tmp) not throw an error?


why it should throw a referenceError


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

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.


$ b我想,问题是bable设置。


所以,也许这是一个巴贝尔的错误?
https://github.com/babel/babel.github.io / issues / 826

推荐答案

你是对的,在ES6中这确实会引发异常。它不适合你的原因有两个:

You are correct, in ES6 this does throw an exception. There's two reasons why it doesn't for you:


  • node.js已经实现 - 但它只能在严格模式下正常工作。您应该使用它。

  • babel默认情况下似乎不会转换TDZ,因为它非常复杂并导致冗长的代码。但是,您可以使用 es6.blockScopingTDZ / es6.spec.blockScoping 选项启用它(但我不确定这是否仅适用于Babel 5以及Babel 6中发生的事情。)

  • node.js already implemented let - but it works correctly only in strict mode. You should use it.
  • babel does not appear to transpile the TDZ by default, as it is quite complicated and leads to lengthy code. You can however enable it with the es6.blockScopingTDZ/es6.spec.blockScoping option (but I'm not sure whether this worked in Babel 5 only and what happened in Babel 6 to them).

这篇关于为什么这段代码不会导致ReferenceError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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