分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

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

发布时间:2023-09-06 02:32责任编辑:胡小海关键词:作用域

在代码块外

声明前使用

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved