0

I am trying to use closures in Typescript inside a loop, but I've got some serious problems:

for(let vehicle of vehicles) {
    update(location => 
        {
            vehicle.location = location;
        }
    );
}

I am using Typescript 1.8.1 and I need to target ES5, when I compile the following error shows:

Loop contains block-scoped variable 'vehicle' 
referenced by a function in the loop. 
This is only supported in ECMAScript 6 or higher.

If i use var instead of let in the loop, it uses last value of vehicle for all closures.

Is there any good workaround for this problem when targeting ES5?

Jarek
  • 7,425
  • 15
  • 62
  • 89
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Ruan Mendes Apr 13 '16 at 12:12

3 Answers3

2

Is there any good workaround for this problem when targeting ES5?

Please update to TypeScript nightly. This feature is supported there and will eventually make it to a release.

More

https://basarat.gitbooks.io/typescript/content/docs/getting-started.html#nightly-typescript

basarat
  • 261,912
  • 58
  • 460
  • 511
0

This is a problem because the function you calling in update is bound to the variable vehicle, not the loop iteration vehicle. You would need to do something like:

for(let vehicle of vehicles) {
    (vehicleClosure => {
        update(location => vehicleClosure.location = location)
    })(vehicle)
}

Or use a JavaScript runtime that supports scoping via let which should behave as intended.

ArcSine
  • 648
  • 6
  • 14
0

Yes, bind the function that is using the closure variable, that will create a separate vehicle reference for each of the inner functions in the loop

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

for(let vehicle of vehicles) {
    update(function(veh, location)  {
        veh.location = location;
    }.bind(null, vehicle));
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217