首页 > Web开发 > 详细

[JS] 关于变量作用域的 undefined 和 error

时间:2019-02-11 15:51:57      阅读:169      评论:0      收藏:0      [点我收藏+]

在代码块外

声明前使用

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内访问letconst变量都会产生runtime error,只有遇到声明语句时才会把它从TDZ里移出并正常使用。

[JS] 关于变量作用域的 undefined 和 error

原文:https://www.cnblogs.com/wanyi/p/10361933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!