Improving Function.prototype.bind

Andrea Giammarchi andrea.giammarchi at gmail.com
Thu Jan 5 16:47:49 PST 2012


Guys, by any chance we can go back into the topic?
I was not thinking about changing the meaning of "this" in a function, also
Python sends explicit self context as first argument so things are slightly
different in any case ....

Point is:
  - bind was one of the most needed/used Function.prototype ever, the
reason ES5 adopted it out of Prototype library
  - bind is over-enginered for 90% of use cases and it easily leads to
anti-patterns due inability to retrieve already bound functions/objects and
the need to address somewhere everything if we want to remove, as example,
a listener
  - bind, as it is, is more than fine, and developers got use to it, it
does not mean that developer could understand an Object.prototype related
method able to create and retrieve the unique function bound with that
object as context

I am seeing stuff like this everywhere

this._boundMethod = this.method.bind(this);

and in my opinion is even ugly to read ... first of all is redundant all
over the place, secondly the bound method is, in this way, easily exposed
outside.

A private scope per each instance so that bound method would be a private
variable makes even less sense ... plus bind, used with the single context
argument, is a context matter, and a single context argument, should never
be recreated unless strictly necessary but today I have still never seen
the usage for a new bound function/object used as freshly new created
object.

Nobody is using/creating two context bound on purpose so that

sameCallback.bind(sameObject)
should always be ===
sameCallback.bind(sameObject)

since the scope the callback has been created won't ever change during app
lifecycle, and accordingly it does not make sense at all to create two
different results/functions/objects

I don't want to break bind as it is, all I am proposing is to bring
Object.prototype.boundTo/asContextOf in core so that GC life is easier and
performances much fasters than whatever WeakMap or proper method, to avoid
leaks, could do.

sameObject.boundTo(sameCallback) === sameObject.boundTo(sameCallback)

is a simple method that could change 90% of frameworks out there and it's
shimmable, through my code, or others libraries.

Any thoughts on this ?
It's just needed, so if you have a better idea, since those exposed until
now do not scale or are not faster/shimmable, I'd like to listen to it.

Thanks and Best Regards
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120106/cf7265af/attachment.html>


More information about the es-discuss mailing list