看似简单的一道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遗留兼容性语义的一部分,所以不要在块内声明函数,也不要依赖此代码以这种方式运行。
这里也解释了这一点

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容