首页 > 解决方案 > 理解匿名函数在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/

只是想了解在这种情况下匿名是如何工作的

标签: javascriptanonymous-functionlexical-scope

解决方案


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


推荐阅读