Reputation: 7729
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?
Upvotes: 0
Views: 757
Reputation: 275819
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.
https://basarat.gitbooks.io/typescript/content/docs/getting-started.html#nightly-typescript
Upvotes: 2
Reputation: 92274
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));
}
Upvotes: 0
Reputation: 644
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.
Upvotes: 0