Autobinding destructuring

Brendan Eich brendan at mozilla.org
Sat Aug 4 13:19:08 PDT 2012


David Bruant wrote:
>     var context = 
> document.getElementsByTagName('canvas')[0].getContext('2d');
>
>     // bikeshed syntax for binding destructuring, my point isn't about 
> syntax here
>     var #{beginPath: begin, moveTo, lineTo, stroke, closePath: end} = 
> context;
>     // extracted methods are bound to the context object.
>

The # was somewhat wanted for records, tuples, and const functions, once.

Appreciate that the # syntax is straw, so permit me to light the match. 
The challenge is to put the |this| binding on the left-hand side, 
without making the pattern language not be covered by the object and 
array literal subgrammar or a plausible extension of it. One idea:

     var {beginPath: begin, moveTo, lineTo, stroke, closePath: 
end}.bind(context) = context;

In a binding or even lvalue context, this would make a special form 
without adding syntax or reserving bind otherwise. It does require 
repeating |context| on LHS where that occurs on the RHS, though.

For DRY, new syntax seems required. From

http://wiki.ecmascript.org/doku.php?id=strawman:bind_operator

we would write

     var begin = ::context.beginPath;

to extract just one bound method reference.

(Note that :: was wanted for guards too, so its use here is straw of a 
flammably dry kind. Note also that the grammar in the strawman under 
"Syntax" is not complete.)

The equivalence between let foo = obj.bar; and let {bar: foo} = obj; 
suggests

     var {beginPath: begin, moveTo, lineTo, stroke, closePath: end} = 
::context;

but this separates the :: on the RHS from the destructuring on the LHS.

Could we instead make :: part of the pattern language too? It would be 
covered by the (corrected) grammar in Dave's bind operator proposal.

     var ::{beginPath: begin, moveTo, lineTo, stroke, closePath: end} = 
context;

Your wish to mix auto-bound and unbound method destructuring could be 
met by:

     var {unbound, ::bound} = object;

which could be written without destructuring, but with the bind operator 
strawman, as

     var unbound = object.unbound, bound = ::object.bound;

/be


More information about the es-discuss mailing list