简体   繁体   English

retutn func() 或从 func() 返回没有 () 的 func,代码会发生什么?

[英]retutn func() or return func without () from func(), what happens with code?

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

please help me to understand the difference between - return f and f().请帮助我理解 - return f 和 f() 之间的区别。 what happen with function code when activate return f?激活返回 f 时 function 代码会发生什么? how it work?它是如何工作的? why console.log(f) return a number?为什么 console.log(f) 返回一个数字? i know f() return result, but return f?我知道 f() 返回结果,但返回 f? i dont understand.我不明白。

In Javascript functions are first class objects .在 Javascript 中,函数首先是 class 对象 You can treat a function like any other variable or object, and pass them to functions, assign to other variables, and (as in this case) return them from functions.您可以像对待任何其他变量或 object 一样对待 function,并将它们传递给函数,分配给其他变量,并(如在本例中)从函数中返回它们。

A perhaps simpler example to show it might be something like一个可能更简单的例子来展示它可能是这样的

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

My own example here is quite useless and only to show the principle.我自己在这里的例子是没有用的,只是为了说明原理。 For a more useful example it's common for functions to return references to other functions, like in the example inside the question.对于一个更有用的示例,函数返回对其他函数的引用是很常见的,就像问题中的示例一样。

It happens to be that when you try to console.log any value it invokes "toString" method.碰巧的是,当您尝试 console.log 任何值时,它都会调用“toString”方法。

In your instance you override toString method instead of default implementation it returns a number在您的实例中,您覆盖 toString 方法而不是默认实现,它返回一个数字

The function without the () is a pointer to the function.没有 () 的 function 是指向 function 的指针。 I use it with setTimeout all the time.我一直将它与 setTimeout 一起使用。

function doSomething() {
    console.log('something');
}

setTimeout(doSomething, 5000);

Each time you invoke sum function, you are always returning reference of function f.每次调用 sum function 时,总是返回 function f 的引用。 So sum(1) will return the reference of f, while sum(1).toString() will return the 1 sum(1)(2) will return reference of f, while sum(1)(2).toString() will return 3所以 sum(1) 将返回 f 的引用,而 sum(1).toString() 将返回 1 sum(1)(2) 将返回 f 的引用,而 sum(1)(2).toString()将返回 3

It is not recursion because you returning just the reference.这不是递归,因为您只返回引用。 So until you invoke it, the function is not called因此,在您调用它之前,不会调用 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM