18.104.22.168 Array.prototype.reduce ( callbackfn [ , initialValue [ , thisArg ] ] )
david.hopwood at industrial-designers.co.uk
Sat Mar 21 10:22:36 PDT 2009
Edward Lee wrote:
> 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)
Very minor. '.bind(this)' has the advantage of working in general for all
such cases, not just for particular Array methods.
In the "thisless" style where objects are constructed as closures rather
than using prototypes, of course, this problem never happens.
> But the main reason is just consistency with the rest of the functions
> that take a callback.
I accept that consistency is a valid consideration; I just don't think it
outweighs the considerations given in my previous post. I'm not strongly
opposed to adding 'thisArg' to these functions, though, if the concensus
is in favour. My argument is primarily that they're not needed and that
it is better for programs to use variable capture, and either the
thisless style or '.bind(this)', instead.
David-Sarah Hopwood ⚥
More information about the Es-discuss