简体   繁体   中英

How can functions be called as an argument for a function?

The code that brought this question to my mind (and that I am trying to understand) is:

function sum(numbers) {
    var total = 0;
    forEach(numbers, function (number) {
        total += number;
    });
    return total;
}
show(sum([1, 10, 100]));

ps forEach is a function that does this:

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
        action(array[i]);
}

I would like an explanation of how the code above works, as I don't understand how a function can be called as an argument for a function.

I'm mostly concerned about how a function can be called as an argument for a function.

It's not called in the argument - the function itself is passed. In JavaScript, functions are first-class values ; they are objects which can be invoked with parenthesis, but they also have normal properties (like .prototype or .name ) and inherited methods (like .call , .bind ). Have a look at the docs for Function objects .

Your sum code is creating an anonymous function, and passes the reference to it into the forEach function where it is stored in the action variable. It then is getting invoked from there.

The concept of passing functions around to be invoked with values determined by another method is named callbacks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM