Item 22: Use arguments to Create Variadic Functions
Item 21 describes a variadic average function, which can process an
arbitrary number of arguments and produce their average value. How
can we implement a variadic function of our own? The fixed-arity ver-
sion, averageOfArray , is easy enough to implement:
function averageOfArray(a) {
for (var i = 0, sum = 0, n = a.length; i < n; i++) {
sum += a[i];
}
return sum / n;
}
averageOfArray([2, 7, 1, 8, 2, 8, 1, 8]); // 4.625
The definition of averageOfArray defines a single formal parameter, the
variable a in the parameter list. When consumers call averageOfArray ,
they provide a single argument (sometimes called an actual argu-
ment to distinguish it clearly from the formal parameter), the array of
values.
The variadic version is almost identical, but it does not define any
explicit formal parameters. Instead, it makes use of the fact that
JavaScript provides every function with an implicit local variable
called arguments . The arguments object provides an array-like interface
to the actual arguments: It contains indexed properties for each actual
argument and a length property indicating how many arguments were
provided. This makes the variable-arity average function expressible
by looping over each element of the arguments object:
function average() {
for (var i = 0, sum = 0, n = arguments.length;
i < n;
i++) {
sum += arguments[i];
}
return sum / n;
}
Variadic functions make for flexible interfaces; different clients can
call them with different numbers of arguments. But by themselves,
they also lose a bit of convenience: If consumers want to call them
with a computed array of arguments, they have to use the apply
method described in Item 21. A good rule of thumb is that whenever
you provide a variable-arity function for convenience, you should also
provide a fixed-arity version that takes an explicit array. This is usu-
ally easy to provide, because you can typically implement the variadic
function as a small wrapper that delegates to the fixed-arity version:
function average() {
return averageOfArray(arguments);
}
This way, consumers of your functions don’t have to resort to the
apply method, which can be less readable and often carries a perfor-
mance cost.
Things to Remember
? Use the implicit arguments object to implement variable-arity
functions.
? Consider providing additional fixed-arity versions of the variadic
functions you provide so that your consumers don’t need to use the
apply method.
文章来源于:Effective+Javascript编写高质量JavaScript代码的68个有效方法 英文版