Improving Function.prototype.bind

David Bruant bruant.d at gmail.com
Fri Jan 6 03:42:12 PST 2012


Le 06/01/2012 12:23, Andrea Giammarchi a écrit :
> it doesn't ... as soon as you release the reference to o no leaks 
> persists but of course until you keep o on hold those unique callbacks 
> cannot be released ...
If you're telling me that keeping only one of the object or the function 
alive but not both keeps the bound function alive, then you do have a 
leak. The bound function only has a reason to exist if both the object 
and the function remain in the program.


> but this would be true with WeakMap too, isn't it?
No it wouldn't. Since WeakMaps keep weak references, you can't have the 
type of leaks I just described. As I said in [1], the bound function 
will be kept in memory only if both the object and the function are 
still strongly held somewhere (so the weakmap doesn't count).

>
> In any case, boundTo is suitable for listeners and the whole point is 
> to do not hold manually those function
>
> once again
>
> window.addEventListener("whatever", o.boundTo(o.method), false);
> // later on
> window.removeEventListener("whatever", o.boundTo(o.method), false);
> // that's it
>
> We can reuse/add the listener later on without problems but as soon as 
> object "o" will be unreachable (no reference count === 0)
"Reference count === 0" and "unreachable" are different properties.
An object can be unreachable even with a reference count different of 0.


> everything will be fine
>
> This, versus this anti pattern
>
> o._leMethodBound = o.method.bind(o);
> window.addEventListener("whatever", o._leMethodBound, false);
> // later on
> window.removeEventListener("whatever", o._leMethodBound, false);
>
> o._leMethodBound is exposed
only because of your implementation.

> and used only to hold a bound method ... we have all done this until 
> now, and to me it's kinda illogical, boring, error prone
I fully agree with your use case. Yet, you still haven't answered my 
question:
If browsers implemented your proposal, it would certainly be in new 
versions that will certainly already have WeakMaps built-in. In this 
case, what would be the benefit of a native implementation rather than a 
library of yours?

Regarding your earlier argument about 'bind' being often implemented in 
libraries, it has to be noted that ES5 version of bind has features that 
ES3-based polyfill cannot emulate including being safe against 
redefinition of 'call' and 'apply'.

David

[1] https://mail.mozilla.org/pipermail/es-discuss/2012-January/019306.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120106/5a59e987/attachment.html>


More information about the es-discuss mailing list