Improving Function.prototype.bind

Andrea Giammarchi andrea.giammarchi at gmail.com
Thu Jan 5 08:07:03 PST 2012


that would not solve much 'cause you can bind a function to a single object
and no more.

My proposal is object related so that eventually, even if you forget to
explicitly drop already bound callbacks, those stacks should be GCed
automagically and memory speaking it should be safe.

@Jake I find that a bit too much universal approach, I mean ... it does not
real scale and it may be redundant in many cases, as example when you
simply have the right context in a function and you call other via this
where the bound one would not be necessary.

Object.prototype.bindAll could be, in any case, a nice addiction, except we
need proxies for runtime added/borrowed methods when/if necessary otherwise
the risk is double bound without reasons and at that time the problem about
listeners would still be there.

regards

On Thu, Jan 5, 2012 at 4:52 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

> On Jan 5, 2012, at 14:54 , Andrea Giammarchi wrote:
>
> Here the whole post with better examples plus the proposed solution that
> would be nice to have in JS.Next
>
> http://webreflection.blogspot.com/2012/01/improving-functionprototypebind.html
>
>
> I don’t use bound() and function expressions very often (I prefer that =
> this for most use cases).
>
> However, the register/unregister pitfall is indeed real. How about the
> following solution?
>
>     Function.prototype.attachTo = function (obj) {
>         this.bound = this.bind(obj);
>         return this;
>     }
>
>     var obj = {
>         mymethod: function () {
>             // ...
>         }.attachTo(obj)
>     }
>
>     generic.addEventListener("stuff", obj.mymethod.bound, false);
>     generic.removeEventListener("stuff", obj.mymethod.bound, false);
>
> Python always binds methods that you access via obj.mymethod. Multiple
> accesses are equal (which I think is carried over to data structures), but
> not the same reference.
>
> It’s a shame that we are really close in JavaScript, with the ECMA-262
> specification using references.
>
> --
> Dr. Axel Rauschmayer
> axel at rauschma.de
>
> home: rauschma.de
> twitter: twitter.com/rauschma
> blog: 2ality.com
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120105/9a385a9b/attachment.html>


More information about the es-discuss mailing list