简体   繁体   English

对 { } 中的 function 声明感到困惑

[英]confused about function declaration in { }

 var a; if (true) { a = 5; function a() {} a = 0; console.log(a) } console.log(a)

I saw the code above, a function is declared in {}.我看到上面的代码,在{}中声明了一个function。 I think it would print 0 0, but it prints 0 5我认为它会打印 0 0,但它会打印 0 5

The following happens:会发生以下情况:

(1) There exist two variable declarations a , one inside the block and one outside of it. (1) 存在两个变量声明a ,一个在块内,一个在块外。

(2) The function declaration gets hoisted, and bound to the inner blocks variable. (2) function 声明被提升,并绑定到内部块变量。

(3) a = 5 is reached, which overrides the block variable. (3) 达到a = 5 ,覆盖块变量。

(4) the function declaration is reached, and the block variable is copied to the outer variable. (4)到达function声明,将块变量复制到外层变量。 Both are 5 now.现在两人都5岁了。

(5) a = 0 is reached, which overrides the block variable. (5) 达到a = 0 ,覆盖块变量。 The outer variable is not affected by this.外部变量不受此影响。

 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¹);

This is actually not really part of the specification, it is part of the web legacy compatibility semantics , so don't declare functions inside blocks and don't rely on this code to behave in this way .这实际上并不是规范的一部分,它是web 遗留兼容性语义的一部分,因此不要在块内声明函数也不要依赖此代码以这种方式运行

This is also explained here这也解释了here

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

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