18.104.22.168 Array.prototype.reduce ( callbackfn [ , initialValue [ , thisArg ] ] )
david.hopwood at industrial-designers.co.uk
Sat Mar 21 07:50:36 PDT 2009
Edward Lee wrote:
> Right now .reduce doesn't take an optional thisArg, so the callback
> is always called with |null| for |this| per 9.c.ii.
> The Array prototype object take an optional thisArg for every, some,
> forEach, map, and filter; so it would be good to make reduce
> consistent with the rest.
Why is it better to use 'this' than to simply have the callback function
capture the variables it needs? The latter is just as expressive and
IMHO results in clearer code, since:
- the captured variables are named, and the names can be more
meaningful than 'this';
- there can be more than one such variable, without needing to set
'this' to an object or list.
The required variables are necessarily in scope when passing a
FunctionExpression as the callback. The case where they are not in scope
because the callback function is defined elsewhere is quite unusual;
in that case, you can instead pass a lambda expression that calls the
function defined elsewhere with these variables as explicit parameters.
(That is a situation where using 'this' results in particularly *unclear*
code, because the definition of what 'this' is set to may be far away
from its use.)
The other methods with callbacks take a 'thisArg' not because it is
needed or even useful, but for compatibility, because they already do
in existing implementations that provide these functions.
David-Sarah Hopwood ⚥
More information about the Es-discuss