Autobinding destructuring
David Bruant
bruant.d at gmail.com
Sat Aug 4 08:43:44 PDT 2012
Le 03/08/2012 17:45, David Bruant a écrit :
> (...)
> It reminded me of an ECMAScript Regret submitted by Tom about the fact
> that method are extracted unbound by default.
> And after a couple of tweets related to 'with' and the canvas API I
> wonder: would it be worth having another syntactic form doing bound
> method extraction? I don't have an idea of what the syntax would look
> like, but it seems like a valuable idea.
Here is how it would look like (adapted from [1]):
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.
begin();
for(var t=0; t <= 2*PI; t += DRAWING_STEP){
x0 = x1;
y0 = y1;
x1 = x + R*cos(t)*cos(angle) - r*sin(t)*sin(angle);
y1 = y - R*cos(t)*sin(angle) - r*sin(t)*cos(angle);
moveTo(x0, y0);
lineTo(x1, y1);
stroke();
}
end();
// Draw Major and Minor Axes
context.strokeStyle = "#FF0000";
begin();
moveTo(x+R*cos(angle), y-R*sin(angle));
lineTo(x-R*cos(angle), y+R*sin(angle));
moveTo(x+r*sin(angle), y+r*cos(angle));
lineTo(x-r*sin(angle), y-r*cos(angle));
stroke();
end();
To me, this looks easier to read than the original. I have no special
bound to the #{} syntax; I just used that to differenciate from
non-binding destructuring. A feature that would be nice would be to be
able to nest binding and regular destructuring, but I don't know if my
bikeshed syntax allows that.
David
[1]
https://github.com/DavidBruant/ShapeGuesser/blob/1a69b7a0a86b6f22225e3b89b31038028d99a478/shapeguesser.js#L21
More information about the es-discuss
mailing list