You're not actually creating a closure at the time you define the anonymous function. If you're familiar with other types of ECMAScript closures (e.g. Javascript closures), Actionscript follows the same pattern. Closures are created at the end of the function call. Because the value of i at return time is 4, the values for i in all the closures that you create are 4.

You can solve this by creating a seperate function that's responsible for creating the closure. For example:

Sure. Skider stated that the reason for this behavior is that closures aren't created until the end of the function. I think my example shows that's not the case, because otherwise, the output would be

5

5

5

since foo is '5' at the end (unless I misunderstood what Skider was saying). You're right--it is about the timing of the execution and what the environment you close over (in this case, the variable reference 'foo') looks like *at the time of closure execution*--not at the time of closure definition.

When you define another wrapper function, as in your example, you're closing over that function's argument, which will not change in this case, since it only lives in the scope of the f2 function.

You are entirely right. My mistake. The reason that i is 4 each time that it's called is because it's called after the function's execution finishes, and at that time the value is 4. Please excuse my temporary insanity.