【问题标题】:How function declaration is affecting hoisting? [duplicate]函数声明如何影响提升? [复制]
【发布时间】:2021-11-03 20:46:53
【问题描述】:

尽管没有调用内部函数,但下面的两个代码会打印不同的输出。

var a = 1;
function foo(){
  a= 2;
}
foo();
console.log(a);   // 2

但是如果我添加一个同名的函数,输出是不同的。虽然我没有打电话给a()

var a = 1;
function foo(){
  a= 2;
  function a(){
    a = 3;
  }
}
foo();
console.log(a);   // 1

不应该是2吗?为什么它记录 1?

【问题讨论】:

标签: javascript hoisting


【解决方案1】:

因为名为 a 的标识符直接在 foo 函数内声明,所以在 foo 函数内对名为 a 的变量的赋值将引用该(本地)标识符,而不是任何可能的名为 @987654325 的外部变量@。就像:

var a = 1;
function foo(){
  // there an identifier named `a` initialized in this scope
  var a;
  // function declarations are hoisted
  a = function a(){
    a = 3;
  }
  // assignment to local identifier `a`
  a= 2;
}
foo();
console.log(a);   // 1

【讨论】:

  • 我理解并感谢您的回答,但我会尽量简单地说,由于 foo 中的函数声明,在 foo 中声明了一个名为 a 及其范围的新变量仅限于foo,它根本不会影响外部a。没有函数声明,外部a 被更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多