对{}中的函数声明感到困惑


18

var a;
if (true) {
  a = 5;

  function a() {}
  a = 0;
  console.log(a)
}
console.log(a)

我看到了上面的代码,在{}中声明了一个函数。我认为它会打印0 0,但它会打印0 5



1
在严格模式下,它记录0 undefined
某些性能

@certainPerformance很好,这是可以解释的,但是我无法解释这是否a = 5会成为障碍。据贝尔吉的骗局,function a将其吊起。
乔纳斯·威尔姆斯

2
似乎在到达函数声明时,将局部作用域的块变量复制到了外部块。
乔纳斯·威尔姆斯

Answers:


13

发生以下情况:

(1)存在两个变量声明a,一个在块内,一个在块外。

(2)函数声明被吊起,并绑定到内部块变量。

a = 5到达(3),它将覆盖block变量。

(4)到达函数声明,并将块变量复制到外部变量。现在两个都是5。

a = 0达到(5),它将覆盖block变量。外部变量不受此影响。

 var a¹;
 if (true) {
   function a²() {} // hoisted
   a² = 5;
   a¹ = a²; // at the location of the declaration, the variable leaves the block      
   a² = 0;
  console.log(a²)
}
console.log(a¹);

实际上,这实际上不是规范的一部分,它是Web遗留兼容性语义的一部分,因此不要在块内声明函数也不要依赖此代码以这种方式运行

这也在这里解释


但是为什么在到达函数声明后,将块变量复制到外部变量呢?
Chor

@Chor,规范说是这样。我不知道为什么。
乔纳斯·威尔姆斯
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.