看似简单的一道js题

下面js运行结果是?

var a
if(true){
    a = 5
    function a(){}
    a = 0
    console.log(a)
}
console.log(a)
//运行结果
// 0
// 5

要是对答案困惑可以参考这个解释: https://stackoverflow.com/questions/58619924/confused-about-function-declaration-in/58620404#58620404
更底层的原理可以参考 ES6中块级作用域中函数的语义:https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6

参考中这样说的:

The following happens:
(1) There exist two variable declarations a, one inside the block and one outside of it. //存在两个变量声明a,一个在块内部,一个在块外部。
(2) The function declaration gets hoisted, and bound to the inner blocks variable. //函数声明被提升,并绑定到内部块变量。
(3) a = 5 is reached, which overrides the block variable. //a=5,覆盖内部块变量。
(4) the function declaration is reached, and the block variable is copied to the outer variable. Both are 5 now. //函数声明,内部块变量复制到外部变量。他们现在是5了。
(5) a = 0 is reached, which overrides the block variable. The outer variable is not affected by this. //a=0,覆盖内部块变量。外部变量不受此影响。

 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.
This is also explained here
这实际上并不是规范的一部分,它是web遗留兼容性语义的一部分,所以不要在块内声明函数,也不要依赖此代码以这种方式运行。
这里也解释了这一点

你可能感兴趣的:(看似简单的一道js题)