Improving Function.prototype.bind

John J Barton johnjbarton at
Sun Jan 8 10:47:38 PST 2012

On Thu, Jan 5, 2012 at 11:47 PM, Andrea Giammarchi <
andrea.giammarchi at> wrote:

> ...
> P.S. is it really just me that see the problem with current bind ?
> On Fri, Jan 6, 2012 at 2:22 AM, Brendan Eich <brendan at> wrote:
>> On Jan 5, 2012, at 4:47 PM, Andrea Giammarchi wrote:
>> Right now the lack of memoization is not a burning issue, from what I
>> hear. You've raised it, I think for the first time on es-discuss.
>> /be
Since I agree with Andrea that the .bind() is a problem and since Brendan
does not, I want to restate Andrea's case based on my experience.

The ingredients for this problem are exactly the ones around when bind()
was invented: DOM event registration and JS methods.

The event registration 1) accepts a function, 2) requires explicit cleanup:
   window.addEventListener('load', boundOnLoad, false);
   window.removeEventListener('load', boundOnLoad, false);
The JS method 1) must be bound to the correct object 2) be reference-able
for the removeEventListener.

This combination prevents simple inline functions so commonly used by JS
devs from being applied to DOM event registration, a very common use of
inline functions. If you use an inline function without bind(), then it
will not have the correct object binding; if you use an inline function
with bind(), then it will not be reference-able for the remove.  Therefore
you must use a reference to a bound function as the handler and it must be
a property of an object or a scope you close over.  That is why our code is
now littered with:
   baz.boundOnLoad = baz.onLoad.bind(baz);  // bah, JS voodoo
In my code I now have a function _bindListeners() called from initialize()
where I list all of this goop.  The tedium is similar to reference counting.

Note also my recent thread about anonymous methods, ie replacing
"boundOnLoad" with imaginary "this.function(event) {...}"; I was prompted
to float this idea because it is another approach to the above problem.

Yet another approach would mark methods as bound at declaration:
  this.onLoad = function(event) {...}.bind(this);
This approach (and other postfix solutions) are hard to follow since the
... pushes the salient info far from the name. (Plus this is a trap,  you
have to be careful not to use it in literals).

I don't know if Andrea's solution is good or not, but I want to put another
vote for |"this| is a problem".

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list