【发布时间】:2018-06-02 08:13:38
【问题描述】:
当我看到一段代码并试图理解为什么称它为匿名时,我有点困惑。
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?
它在博客中说 “当你调用加法器时,即inner_function,由于词法作用域,它可以访问total,即使拥有total.total的函数本身是在很久以前返回的函数的范围内声明的。” http://pierrespring.com/2010/05/11/function-scope-and-lexical-scoping/
只是想了解在这种情况下匿名是如何工作的
【问题讨论】:
-
total 的值不会保留,因为如果您不调用匿名函数,则不会设置任何值...在这种情况下,total 将是未定义的。
-
@Andreas 我不认为这是重复的,但那里的信息将有助于回答这个问题。
-
当我不调用匿名函数而是调用 adder(2) 时,我想了解什么,它不会作为总数传递吗?
-
采用
total的函数使用(0)调用,而不是inner_function。顺便说一句,两者都不是完全匿名的(例如,let x = () => 0, y = x; console.log(y.name);可以看到)但我想这是一个技术细节。而且我也认为这是重复的,这个话题很令人困惑,是的,但已经经常被问到了。
标签: javascript anonymous-function lexical-scope