Autobinding destructuring

Claus Reinke claus.reinke at talk21.com
Sat Aug 4 14:48:22 PDT 2012


> 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.

>     // 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?

    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);
 



More information about the es-discuss mailing list