首页 > 解决方案 > retutn func() 或从 func() 返回没有 () 的 func,代码会发生什么?

问题描述

function sum(a) {

  let currentSum = a;

  function f(b) {
    currentSum += b;
    return f;
   }

  f.toString = function() {
    return currentSum;
  };
  console.log(f);
  return f;
}

alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6

请帮助我理解 - return f 和 f() 之间的区别。激活返回 f 时功能代码会发生什么?它是如何工作的?为什么 console.log(f) 返回一个数字?我知道 f() 返回结果,但返回 f?我不明白。

标签: javascriptfunctionreturn

解决方案


在 Javascript 中,函数是第一类对象。您可以将函数视为任何其他变量或对象,并将它们传递给函数,分配给其他变量,并(如本例中)从函数中返回它们。

一个可能更简单的例子来展示它可能是这样的

function foo() {
    console.log("foo called");
}

bar = foo;  // Assign the function foo to the variable bar
            // Note that this doesn't actually call foo

bar();  // Now we call the foo function

我自己在这里的例子是没有用的,只是为了说明原理。对于一个更有用的示例,函数返回对其他函数的引用是很常见的,就像问题中的示例一样。


推荐阅读