javascript - 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?我不明白。
解决方案
在 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
我自己在这里的例子是没有用的,只是为了说明原理。对于一个更有用的示例,函数返回对其他函数的引用是很常见的,就像问题中的示例一样。
推荐阅读
- python - 用 Celery 设置 django 项目
- java - 多米诺骨牌的 Android Studio 底层数据结构
- gulp - 无法使用 gulp 执行自动化测试
- vb.net - 如何为我的计算器实现两个文本框的使用?
- javascript - 使用 PJAX 和 Three.js 的网站速度问题?
- c++ - 如何为不同链接共享库中定义的相同函数生成链接器警告?
- php - 在 Windows 上安装 PHP 7 的作曲家以获取 PHPmailer 时遇到问题
- c++ - 如何从 Windows 应用程序输出到标准输入?
- javascript - 有没有办法在 Bucklescript 类型注释中表示 JS 模板文字?
- xcode - 从 VS2017 和 xcode 7.3.1 构建时,RemoteBuild 提供部署 404