I have this:
for (var i:int = 0; i < 3; i++) {
var newChoice:MainButton = new MainButton(function(){
trace(this["func" + i])} );
}
public function func0 ...
public function func1 ...
public function func2 ...
(When clicked, MainButton calls the function in the argument)
However, I get func3, which I assume is do to it finding the value of i. But shouldn’t it pass by value since it’s a number? How do I get the wanted result? Thanks
You’re not passing anything, except the function itself (which is passed by reference).
What’s happening is that the function creates a closure around the variable
i, changing its lifetime. When the anonymous function is called,iis still in its original scope, but the loop has already finished, leavingiat 3.So, the closure is essentially keeping
iin the scope of the function even after the original, declaring function has finished.Instead of closing over the variable, you wanted to close over the variable’s value at the time the function is created. You can achieve this with an intermediate variable that’s set only once before being closed over: