[英]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.