lexical for-in/for-of loose end

Herby Vojčík herby at mailbox.sk
Fri Feb 3 02:37:10 PST 2012


Allen Wirfs-Brock wrote:
> for-in works well with a per iteration binding because there is no
> header code that runs between iterations. The various desugarings that
> have been proposed to provide a fresh copy for each iteration of this
> form of for work for propagating simple values between the header and
> each iteration but not for closure captures.
>
> Plus, the desugarings aren't things that are really suitable for
> teaching the semantics to everyday JS programmers. You instead have to
> say something like:
>
>     Ok, this is really complicated but here goes. For each let/const
>     declared in the for header, a fresh variable is located in the loop
>     body for each iteration of the loop. However, the values of the loop
>     variables are automatically copied from the previous iteration into
>     the next iterations. This means that basic expression operator will
>     work in the loop header pretty much like you would expect. But be
>     careful if you use any function expressions in the for header
>     because the loop variables they reference may not be from the
>     current iteration and any changes to loop variable they make may not
>     have the effect you intended. But, hey you probably shouldn't do
>     those things so it really doesn't matter what it really does.

Ok, alternative approach:

for (let i=..., whatever; whatever2; whatever3) {
   // use i
}

be implemented as

let i=..., whatever;
while (whatever2) {
   {
     let i=forward_proxy_to(outer i);
         // a thing that touches real i, but is different object
     // use i
     i=current value of inner i; // fix inner i to the value

     // The point is, it works for closures, both from inside or
     // 'detached' since it is always the same 'i' binding
     // in the same execution context
   }
   whatever3;
}

> Allen

Herby


More information about the es-discuss mailing list