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?

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.