【问题标题】:understanding anonymous function works in javascript code [duplicate]理解匿名函数在javascript代码中工作[重复]
【发布时间】: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 = () =&gt; 0, y = x; console.log(y.name); 可以看到)但我想这是一个技术细节。而且我也认为这是重复的,这个话题很令人困惑,是的,但已经经常被问到了。

标签: javascript anonymous-function lexical-scope


【解决方案1】:

如果您不调用该函数,则还没有total。您的 adder 将引用外部函数。 adder(2) 会将 total 绑定到 2 并返回内部函数(您忽略它)。 adder(3) 会将 total 绑定到 3 并返回另一个内部函数(您也可以忽略它)。

具体来说:

var adder = function (total) {
    var inner_function = function (summand) {
        total += summand;
        alert(total);
    }

    return inner_function;    
};

就像

function adder(total) {
    var inner_function = function (summand) {
        total += summand;
        alert(total);
    }

    return inner_function;
}

然后

adder(2)  // returns `inner_function`

如果您不保存其返回值并调用它,则没有可见的效果。

【讨论】:

  • 那么叫makeAdder会更合适
【解决方案2】:

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。 现在,当您省略调用该函数时,加法器实际上是外层函数,因此像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

【讨论】:

  • 当我们调用匿名时,它如何能够保持总价值并且 adder(2) 和 adder(3) 相加?但如果我不需要调用外部和内部函数来添加值?
  • 查看 Andreas 评论中的链接(关于重复的问题)可以准确回答您的问题。 :)
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 2015-02-19
  • 1970-01-01
  • 2013-12-18
  • 2012-02-23
  • 1970-01-01
相关资源
最近更新 更多