ES6 typeof引发错误 [英] ES6 typeof throws an error
问题描述
ES5 typeof
被认为是安全的,因为当再次检查未声明的值时,它将不抛出ReferenceError
.例如
ES5 typeof
is considered safe, as it will not throw ReferenceError
when checked agains a non-declared value. such as
console.log(typeof undeclaredVar); // undefined
但是,如果在稍后用let
或const
声明了该值,则在es6中检查typeof undeclaredLetConst
时,将仅仅引发错误.如果用var声明,它将正常工作.
however, when checking for typeof undeclaredLetConst
in es6 it will throw an error only if the value was later on declared with a let
or const
. if it was declared with var it will work normally.
console.log(typeof undeclaredLetConst);
let undeclaredLetConst = "hello"; // ReferenceError
那里发生了什么?
推荐答案
为什么与var
声明一起使用
当JavaScript引擎浏览词法作用域块并找到具有var
的变量声明时,它会将声明提升到函数的顶部(如果不存在"use strict"
,则将其声明为全局作用域).
Why it works with var
declarations
When a JavaScript engine looks through a lexical scope block and finds a variable declaration with var
, it hoists the declaration to the top of the function (or global scope if no "use strict"
is present).
因此,typeof
永远不会失败,因为它预先检查了要检查的变量.
Hence the typeof
will never fail as the variable its checking upon will be hoisted beforehand.
TDZ 在ECMAScript规范中从未明确命名,但是该术语用于描述为何在声明之前无法访问let和const声明.
The TDZ is never named explicitly in the ECMAScript specification, but the term is used to describe why let and const declarations are not accessible before their declaration.
为什么它失败并显示const
和let
当JavaScript引擎浏览词法作用域块并找到带有let
或const
的变量声明时,它将声明放置在 TDZ 中.任何尝试访问 TDZ 中的变量的操作都会导致运行时错误.
Why it fails with const
and let
When a JavaScript engine looks through a lexical scope block and finds a variable declaration with let
or const
, it places the declaration in the TDZ. Any attempt to access a variable in the TDZ results in a runtime error.
在流到达声明本身后,在运行时间期间将声明从 TDZ 中删除.
The declaration is removed from the TDZ during runtime once the flow reaches the declaration itself.
console.log(typeof undeclaredLetConst); // "undefined"
if (1) {
let undeclaredLetConst = "no errors!";
}
当执行typeof
操作时,
undeclaredLetConst
不在 TDZ 中,因为它发生在声明undeclaredLetConst
的程序段之外.这意味着没有值绑定,typeof只是返回"undefined".
undeclaredLetConst
isn’t in the TDZ when typeof
operation executes because it occurs outside of the block in which undeclaredLetConst
is declared. That means there is no value binding, and typeof simply returns "undefined".
来源:尼古拉斯·扎卡斯(Nicholas C. Zakas)写的一本很棒的书,了解ECMAScript 6.
Source: An awesome book by Nicholas C. Zakas, Understanding ECMAScript 6.
这篇关于ES6 typeof引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!