这是一个高阶函数的例子。这是一个将函数作为参数并返回函数而不仅仅是常规值的函数(尽管函数在 Javascript中“只是常规值”)。在这种情况下:
function splat(fun) {
splat
将函数作为参数...
return function(array) {
...and returns a new function which takes an array...
return fun.apply(null, array);
...and when called calls the first fun
function with the array .applied
as its arguments.
So splat
takes one function which expects several parameters and wraps it in a function which takes an array of parameters instead. The name "splat" comes from languages like Ruby, where a *
(a "splat" or "squashed bug") in the parameter list of a function accumulates an arbitrary number of arguments into an array.
var addArrayElements = splat(function(x, y) { return x + y });
addArrayElements
is now basically:
function (array) {
// closed over variable:
// var fun = function(x, y) { return x + y }
return fun.apply(null, array);
}
Here this is realized by a closure, which closes over and "preserves" the original fun
passed to splat
in the new returned function.