In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-09-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
这篇文章主要讲解了"如何提升全局变量var",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"如何提升全局变量var"吧!
一、提升全局变量 varvar tmp = new Date(); function f() { console.log(tmp); if (false) { var tmp = "hello"; } } f();
JS新手往往会以为将正常打印出日期,而实际输出的确是`undefined`!
> var tmp = new Date(); > function f() { ... console.log(tmp); ... if (false) { ..... var tmp = "hello"; ..... } ... } > f(); undefined
这是因为在函数f()的内部,var被提升到定义域的顶部,实际执行为:
var tmp = new Date(); function f() { var tmp;// 提升到这里,将全局的tmp覆盖了。var默认赋值为undefined console.log(tmp); if (false) { var tmp = "hello"; } } f();
也就是说var不仅提升,而且将tmp初始化赋值为undefined。
二、如何才能正常输入日期呢?
解决方案是将global-scope的var替换为block-scope的let:
var tmp = new Date(); function f() { //var tmp;// 提升到这里,将全局的tmp覆盖了。var默认赋值为undefined console.log(tmp); if (false) { let tmp = "hello"; } } f(); // 2021-04-02T10:52:30.983Z
这是因为let定义的是local-variable.
三、TDZ临时DeadZones
更加诡异的案例,来单独看let:
var tmp = new Date(); function f() { console.log(tmp); let tmp = "hello"; } f();
你原以为将会如常打印出时间,但却报错tmp未定义。
ReferenceError: Cannot access 'tmp' before initialization
这是因为 tmp 被提升,其实际执行为:
var tmp = new Date(); function f() { let tmp; // 提升在这里 console.log(tmp); let tmp = "hello"; } f();
然而区别于var的是,tmp仅仅被提升,却不会被自动赋值为undefined,因此会报错`ReferenceError`.
该问题就是传说中的TDZ (temporal dead zone)。解决方案也简单,就是将所有的let或者const等全部都写到最上面。
感谢各位的阅读,以上就是"如何提升全局变量var"的内容了,经过本文的学习后,相信大家对如何提升全局变量var这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
About us Contact us Product review car news thenatureplanet
More Form oMedia: AutoTimes. Bestcoffee. SL News. Jarebook. Coffee Hunters. Sundaily. Modezone. NNB. Coffee. Game News. FrontStreet. GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.