Autobinding destructuring

David Bruant bruant.d at
Sat Aug 4 16:06:48 PDT 2012

Le 04/08/2012 17:53, Claus Reinke a écrit :
> [argh, unhelpful hidden key-combo led to premature send]
>> But it also made me realize that by default, destructuring returns 
>> unbound methods. It's perfect for the above use case, but may be 
>> annoying when you wish to extract functions bound to the object 
>> they're extracted from:
>>     var o = {a:1, f: function(){return this.a;}};
>>     var {f} = o;
>>     f(); // throw
> Agreed that this is an obstacle. With operators, one could have a
> convenient binding selection, but the destructuring case needs a
> separate solution.
Why does it need a separate solution? Especially if it's possible in 
destructring to have both bound and unbound?

>> // bikeshed syntax for binding destructuring, var #{beginPath: begin, 
>> moveTo, lineTo, stroke,             closePath: end} = context;
>> // extracted methods are bound to the context object.
> This version, I have issues with: not all items need to be bound,
> so we'd need syntax for subpatterns. In this example, all of the
> bound items are going to be bound to the same context, and that 
> context is on the right hand side, so perhaps we need to do something 
> there? Perhaps
>   let bind_methods = obj =>
>           Proxy(obj,{get(t,n,r) {
>               let  prop = t[n];
>               return prop instanceof Function ? prop.bind(t) : prop }
>            });
>   var {beginPath: begin, moveTo, lineTo, stroke, closePath: end} =
>       bind_methods(context);
> Of course, that won't work if we need binding destructuring
> from sub-objects.
Indeed. It also does not combine bound and unbound.
To some extent, the fact that you've written "prop instanceof Function" 
to test whether prop is a function enforces the idea that it should be 
done through syntax and not a library ;-)


More information about the es-discuss mailing list