Javascript 时间死区 [英] Javascript Temporal Dead Zone
本文介绍了Javascript 时间死区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的不明白下面的代码片段发生了什么.
I don't really understand what's happening with the snippet below.
我预计会因为 Temporal Dead Zone 而出现错误,但看起来 const baz = '123123';
被提升了.
I would expect an error because of the Temporal Dead Zone, but it looks like const baz = '123123';
gets hoisted.
一切正常的原因是什么?
What's the reason why everything works?
class Foo {
constructor() {
console.log('Foo baz is:', baz)
}
}
function log() {
console.log('log baz is:', baz);
}
const baz = '123123';
log();
new Foo();
推荐答案
不需要吊起来.
函数在被调用之前不会尝试访问变量.
The functions don't try to access the variable until they are called.
在定义常量并为其分配值之前不要调用它们.
You don't call them until after the constant is defined and has a value assigned to it.
这篇关于Javascript 时间死区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文