【问题标题】:JavaScript Function Overloading / OverwritingJavaScript 函数重载/覆盖
【发布时间】:2018-06-27 17:39:28
【问题描述】:

我正在努力理解

function test() {
  return 'foo';
}

console.log(test());

test = function() {
  return 'bar';
}

console.log(test());

function test(a, b) {
  return 'baz';
}

console.log(test());
console.log(test(true));
console.log(test(1, 2));

上面的控制台代码

巴兹
酒吧
酒吧
酒吧
酒吧

但作为我所期待的单线程语言和函数重载概念的 JavaScript


酒吧
酒吧
巴兹
呵呵

谁能解释为什么会这样?

【问题讨论】:

    标签: javascript oop overloading


    【解决方案1】:

    一步一步:

    function test() {
      return 'foo';
    }
    

    这是一个函数声明。 test 变量在解释时声明,在运行时之前。

    test = function() {
      return 'bar';
    }
    

    这是一个函数表达式。执行此行时,test 变量将被覆盖。

    function test(a, b) {
      return 'baz';
    }
    

    这是另一个函数声明。 test 变量在运行时再次被覆盖。

    这就是为什么你的第一个版本的测试函数永远不会被调用。因为第二个函数声明在运行前覆盖了它。

    More about function declaration vs. function expressions.

    【讨论】:

      【解决方案2】:

      是的。我认为发生的情况如下:

      1. function test(...) { ... } 声明的函数被提升到当前范围的顶部。因此,使用该语法的函数的两个定义都被提升到顶部,但第二个定义覆盖了第一个,因此结果为“baz”。

      2. 函数表达式未提升,例如test = function (...) {...}。因此,当您将标识符 test 重新分配给该函数表达式时,它将成为脚本其余部分的 test 的值。

      正如已经指出的,您不能在 JavaScript 中重载变量或函数。您可以用新值覆盖 var,这就是您在示例中所做的。令人困惑的是 JavaScript 提升的工作方式。

      如果你想避免提升使用let myFn = function (...) { ... }

      据我所知,这是一行一行的:

      // `test` defined with func declaration, hoisted to top
      function test() {
        return 'foo';
      }
      
      console.log(test);
      console.log(test());
      
      // `test` overwritten with function expression, hoisting has already occurred,
      // `test` identifier will have this value for remainder of script
      test = function() {
        return 'bar';
      }
      
      console.log(test);
      console.log(test());
      
      // `test` overwritten with new func declaration, hoisted to top, but after first declaration
      function test(a, b) {
        return 'baz';
      }
      
      console.log(test);
      console.log(test());
      console.log(test(true));
      console.log(test(1, 2));
      

      【讨论】:

        【解决方案3】:

        Javascript 函数不能有重载,它们只会被覆盖。要获得相同的效果,您需要区分方法中的不同重载。

        function test(a, b) {
          if(b)
             return 'baz';
          return 'foo';
        }
        

        【讨论】:

        • 这并不能完全解释发生了什么。您是否愿意更新您的答案以逐行和逐步进行?例如,函数被声明和提升;函数被声明和提升,覆盖;调用第二个函数;声明的函数被函数表达式等覆盖
        猜你喜欢
        • 2012-04-03
        • 2010-10-30
        • 1970-01-01
        • 2012-07-17
        • 2012-08-08
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多