![](/img/trans.png)
[英]Why is the variable described with let accessible inside the function?
[英]Why is let variable accessible within IIFE & var is not?
这个 IIFE 代码能够访问计数
let count = 0;
(function immediate() {
if (count === 0) {
let count = 1;
console.log(count);
}
console.log(count);
})();
但为什么在这种情况下count未定义?
var count = 0;
(function immediate() {
if (count === 0) {
var count = 1;
console.log(count);
}
console.log(count);
})();
如果您使用var
变量声明被提升,这意味着您的代码将按以下方式重写:
var count = 0;
(function immediate() {
var count; // decalration of variable hoisted on the function scope
// and the count variable now is undefined.
if (count === 0) {
count = 1;
console.log(count);
}
console.log(count); // just this is printed.
})();
如您所见, if块内的变量现在覆盖了全局count 。
这种行为不是很明显的事实是许多人建议避免使用var的原因,因为我们可以使用let和const来代替,它们有一个块 scope。
更新
感谢 @t.niese 的评论,我认为值得一提的是var与let和const之间的另一个区别。
与var一样, let和const被提升,但有以下区别:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.