Improving Function.prototype.bind

Axel Rauschmayer axel at rauschma.de
Thu Jan 5 07:52:13 PST 2012


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/4f87a902/attachment-0001.html>


More information about the es-discuss mailing list