繁体   English   中英

为什么 let 变量可以在 IIFE 中访问而 var 不能?

[英]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的原因,因为我们可以使用letconst来代替,它们有一个块 scope。

更新

感谢 @t.niese 的评论,我认为值得一提的是varletconst之间的另一个区别。

var一样, letconst被提升,但有以下区别:

  1. 他们有一个块 scope 而不是var那样的 function scope
  2. 它们被声明但没有像var那样被初始化为undefined
  3. 任何在初始化之前访问用letconst声明的变量的尝试都将导致ReferenceError异常,而访问未声明的变量或提升的var将只返回undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM