apscience
apscience

Reputation: 7253

AS3 not passing number by value, rather by reference?

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

Upvotes: 1

Views: 507

Answers (1)

Cameron
Cameron

Reputation: 98746

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, i is still in its original scope, but the loop has already finished, leaving i at 3.

So, the closure is essentially keeping i in 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:

for (var i:int = 0; i < 3; i++) {
    var j = i;       // New variable each time through the loop; closure will close over a different variable each time (that happens to have the same name)
    var newChoice:MainButton = new MainButton(function(){
        trace(this["func" + j])} );
}

Upvotes: 4

Related Questions