JavaScript: 使用 var 实现 let-working

JavaScript: implement let-working with var

所以我有一个克隆 let-behavior 的代码。但我不明白它是如何工作的以及为什么工作。有人可以解释一下吗?

(function() {
  var a = 2;
})()

let 的范围是它出现的块。

var 的范围是它出现的函数。

通过用函数(立即调用)替换块,var 的范围与 let 相同。

如果你只能使用 var 变量,但你想确保变量声明不会覆盖另一个预先存在的同名变量,你可以使用 IIFE将该变量作用于函数。这实际上创建了一个 "block",类似于下面的第二个示例。

var 变量的作用域为函数:

var a = 1;
let b = 1;

(function() {
  var a = 2;
  let b = 1;
})();

console.log(a); //=> 1 (a is not overwritten because the second `var a` is function-scoped)
console.log(b); //=> 1

let 变量的范围为块:

let a = 1;
var b = 1;

{
  let a = 2;
  var b = 2;
}

console.log(a); //=> 1 (a is not overwritten as let is block-scoped)
console.log(b); //=> 2 (b is overwritten as var is not block-scoped)

值得一提的是,您可以重新声明一个 var 变量,因此可以覆盖同名的现有 var 变量。但是,您不能重新声明 let 变量:

var a = 1

// will not error as `var` does not prevent redeclaration
var a = 2

let b = 1

{
  // will not error as `b` is not declared in this block
  let b = 2
}

// will error as `b` is already declared in this scope
let b = 3

您可以在 this question and its answers 中阅读有关 letvar 的更多信息。