javascript - 理解匿名函数在javascript代码中的作用
问题描述
当我看到一段代码并试图理解为什么称它为匿名时,我有点困惑。
var adder = function (total) {
// the following function is returned
// and assigned to adder
var inner_function = function (summand) {
total += summand;
alert(total);
}
return inner_function;
}(0) // <- we call the annonymous function
// and assign the returned function to adder
adder(2); // -> 2
adder(3); // -> 5
我不明白的是,如果我不调用匿名函数,它就不会保留总计的值。为什么?没有(0),如果我调用adder(2),它不应该像第一次调用一样保持total的值,然后将internal_function分配给变量adder吗?
它在博客中说:“当您调用 adder 时,即 inner_function,由于词法范围,它可以访问总计,即使具有总计的函数。总计本身是在返回的函数的范围内声明的很久以前。” http://pierrespring.com/2010/05/11/function-scope-and-lexical-scoping/
只是想了解在这种情况下匿名是如何工作的
解决方案
var adder = function (total) {
// the following function is returned
// and assigned to adder
var inner_function = function (summand) {
total += summand;
alert(total);
}
return inner_function;
}(0) // <- we call the annonymous function
// and assign the returned function to adder
adder(2); // -> 2
adder(3); // -> 5
当您0
在行尾调用函数 ( ) 时,实际上是在运行外部函数(接受 的函数total
)并返回内部函数。所以调用后adder
包含inner_function
. 现在,当您省略调用该函数时,加法器实际上是 outer_function,因此调用它时adder(2)
返回的不是值,而是inner_function
. 简单的例子:
var adder = function (total) {
// the following function is returned
// and assigned to adder
var inner_function = function (summand) {
total += summand;
console.log(total);
}
return inner_function;
}
adder(5)(2); // -> 7
推荐阅读
- linux - 使用 sed 在 Docker 中插入第二行(在 shebang 下)
- apache-dubbo - 为什么 dubbo 提供商总是注册到错误的地址?
- java - “如何修复'NoClassDefFoundError:无法在 Android Robolectric 中初始化类 com.google.android.gms.common.GooglePlayServicesUtil' 错误”
- java - 如何处理没有传出端点的 USB-HID 设备?
- css - 如何在 Safari 和 Chrome 中居中占位符文本?
- python - 如何输出到自定义文件描述符?
- sql - SQL Server 如何根据依赖表正确创建视图?
- python - 字典可以用作 matplotlib.pyplot 的完整输入吗?
- firebase - 如何在颤振中从 FirebaseAuth 电话验证方法返回变量?
- windows - 如何为文件调用现代 PrintDialog 窗口