对{}中的函数声明感到困惑 [英] confused about function declaration in { }

查看:59
本文介绍了对{}中的函数声明感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I saw the code above, a function is declared in {}. I think it would print 0 0, but it prints 0 5

推荐答案

发生以下情况:

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

(1) There exist two variable declarations a, one inside the block and one outside of it.

(2)悬挂函数声明,并将其绑定到内部blocks变量.

(2) The function declaration gets hoisted, and bound to the inner blocks variable.

(3) a = 5 ,它覆盖了块变量.

(3) a = 5 is reached, which overrides the block variable.

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

(4) the function declaration is reached, and the block variable is copied to the outer variable. Both are 5 now.

(5) a = 0 ,它覆盖了块变量.外部变量不受此影响.

(5) a = 0 is reached, which overrides the block variable. 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.

此处也对此进行了解释

This is also explained here

这篇关于对{}中的函数声明感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆