在代码块外
声明前使用
a> Uncaught ReferenceError: a is not defined
声明前用typeof
typeof b> "undefined"
声明未赋值就使用
var c;c> "undefined"
在代码块内
没有声明就用
if (true) { ???a;}> Uncaught ReferenceError: a is not defined
if (true) { ???typeof a;}> "undefined"
声明前调用/用typeof
if (true) { ???a; ???let a = 10;}> Uncaught ReferenceError: a is not defined
if (true) { ???typeof a; ???let a = 10;}> Uncaught ReferenceError: a is not defined
分析
在代码块内,JS引擎遇到 var
时会把它提到代码块最前,遇到let
或者const
时会把它加入到暂时性死区(Temporal Dead Zone),在TDZ内访问let
或const
变量都会产生runtime error
,只有遇到声明语句时才会把它从TDZ里移出并正常使用。
[JS] 关于变量作用域的 undefined 和 error
原文地址:https://www.cnblogs.com/wanyi/p/10361933.html