Bound instance-function vending (was RE: Arrow binding)

Domenic Denicola domenic at domenicdenicola.com
Mon Apr 23 12:20:52 PDT 2012


Hmm, so to make sure I understand: the getter-vending is more efficient because it only creates new functions when they are "gotten" (e.g. called or passed to a callback), whereas the closure pattern creates new functions for each instance? Or is there another reason?

It seems like, even if I did create 100 objects, if I called `method` twice on each of them, the closure pattern would win on efficiency.

I suppose it also helps enforce idiomatic expectations, namely that methods are on the prototype. Then again it breaks the idiomatic (and I'd argue more basic) expectation that `myObj.method === myObj.method`, not to mention `myObjInstance1.method === myObjInstance2.method`.

Both of these could be ameliorated with WeakMap caching, but of course virtually nobody is going to write that code. (Unless... time for yet another class library? Hehehe.)

________________________________________
From: Brendan Eich [brendan at mozilla.org]
Sent: Monday, April 23, 2012 14:12
To: Domenic Denicola
Cc: Alex Russell; Russell Leggett; Erik Aarvidson; es-discuss Steen
Subject: Re: Bound instance-function vending (was RE: Arrow binding)

There's a big penalty even in optimizing VMs in adding (the same) method
reference to every instance, vs. sharing it via a prototype. Binding
|this| without new syntax, using whatever (closures, .bind), can be
optimized but it's a challenge and mainly, users do not  do it.

The functional-combinator OOP style Angus advocates, which relies on
.call to delegate, is pretty but it's yet another discipline and not one
I see catching on. The language doesn't make it any easier for users
than for optimizing VM implementors.

The pattern you show below, the "closure pattern", is advocated (e.g. by
crock's book) and it is used. The cost doesn't matter at low object
populations and it's pretty enough, besides being already there, that I
agree it will be hard to beat in my view.

/be

Domenic Denicola wrote:
>> Having done this dance a couple of times, let me suggest to you that the method form will *eventually* end up at a per-class getter on the prototype which vends an instance function which is bound. People will (reasonably) want binding of some sort.
>
> This sounds lovely. I vaguely remember seeing it on es-discuss in the past (for one of the built-ins or proposed built-ins, maybe?). But never in the wild.
>
> I'm curious, though---what advantages does this have over simply setting the method as an instance property? I.e. how does it differ from the following pattern?
>
> function C() {
>      var that = this;
>      that.method = function () {
>          console.log(that);
>      };
> }
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>




More information about the es-discuss mailing list