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? 我不明白。
最佳答案
Javascript 函数为 first class objects 。您可以像对待任何其他变量或对象一样对待函数,并将它们传递给函数,分配给其他变量,并(如本例所示)从函数返回它们。
一个可能更简单的例子来展示它可能是这样的
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
我自己的例子毫无用处,只是为了展示原理。对于更有用的示例,函数通常返回对其他函数的引用,例如问题中的示例。
关于javascript - return func() 或 return func without () 形式 func(),代码会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61658956/