简体   繁体   English

如何调用函数作为函数的参数?

[英]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: ps forEach是执行以下操作的函数:

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 ; 在JavaScript中,函数是一等值 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 ). 它们是可以用括号调用的对象,但它们也具有常规属性(如.prototype.name )和继承的方法(如.call.bind )。 Have a look at the docs for Function objects . 看一下Function对象文档

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. 您的sum代码正在创建一个匿名函数,并将对它的引用传递到存储在action变量中的forEach函数中。 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 . 将函数传递给另一个方法确定的值进行调用的概念称为回调

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何制作可以在Cloud Functions中的其他函数中调用的函数? - How to make a function that can be called in other functions in Cloud Functions? 可以在JS中用参数调用没有参数的函数吗? - Can a function without an argument be called with an argument in JS? 如何将参数传递给使用setTimeout调用的函数? - How can I pass an argument to a function called using setTimeout? 您将如何重写这3个函数,以便一个函数可以调用它? - How would you rewrite these 3 functions so that it can called by one function? gulp函数如何知道内部调用的函数已完成? - How a gulp function can know that functions called inside it are finished? 带有单个参数的javascript函数如何调用带有不同参数的函数? - How can a javascript function, called with single argument, can call function with varying arguments? 萤火虫-如何检测已调用的函数或从何处调用了函数 - firebug - how can I detect what functions have been called or from where a function has been called 这个论点如何进入被调用的函数? - How is this argument making its way to a called function? 如何存储 function 的参数以在内部函数中使用 - How to store the argument of a function to use in inner functions 在href标签中调用参数时,如何将其传递给函数 - How can I pass an argument to a function when I have called it in the href tag
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM