15.4.4.21 Array.prototype.reduce ( callbackfn [ , initialValue [ , thisArg ] ] )

Edward Lee edilee at mozilla.com
Sat Mar 21 09:20:48 PDT 2009


On Sat, Mar 21, 2009 at 9:50 AM, David-Sarah Hopwood
<david.hopwood at industrial-designers.co.uk> wrote:
> Why is it better to use 'this' than to simply have the callback function
> capture the variables it needs?
It's nice to be able to consistently refer to the same 'this' from an
prototype's function whether from inside a local lambda or another
function on that prototype. Any generic function that takes 2
arguments and returns 1 can be used for reduce, but if that callback
if a prototype's function, its 'this' will be wrong unless you
provided extra code to bind the function to an object.

Yes, you can achieve this in other ways by just binding the callback
to the object before passing it to reduce, so one minor benefit is
that it's more compact:

[].reduce(fn, init, this)
[].reduce(fn.bind(this), init)

But the main reason is just consistency with the rest of the functions
that take a callback.

Ed


More information about the Es-discuss mailing list