JavaScript 函数奇怪的行为(函数调用)

时间:2021-07-08 17:31:35

标签: javascript function

function parent() {
  console.log("parent");

  function child() {
    console.log("child1")
  }
  return child();

  function child() {
    console.log("child 2")
  }
}
parent();

输出为:Parent and child2

为什么 child2 不是 child1 而是打印?

3 个答案:

答案 0 :(得分:1)

第二个 child() 覆盖第一个。因此,child 2 打印在控制台中。

如果您在第二个方法下方添加另一个(第三个)child 方法,该方法将运行。

function parent() {
  console.log("parent");

  function child() {
    console.log("child1")
  }
  return child();

  function child() {
    console.log("child 2")
  }
  
  function child() {
    console.log("child 3")
  }
}
parent();

答案 1 :(得分:0)

在 JS 中,如果你写函数同名优先函数。 JS 会重新定义函数,使用之后的函数。这是覆盖

答案 2 :(得分:0)

function declarations 在代码实际执行开始之前被提升(移到顶部)。

因此想象一下 child1 和 child2 函数在顶部,在执行到达 return 语句之前。 类似的东西:

function parent() {
  *****function child() {
    console.log("child1")
  }******

  *****function child() {
    console.log("child 2")
  }******

  *********

  console.log("parent");

  return child();

}

parent();

此外,这里的 child2 函数覆盖了 child1 函数,因此返回了 child2。