Help understanding why this code works - for loop

I have 4 buttons on the stage. I want to assign each button a unique action by using a for loop to assign the actions to these buttons
This example does not work:

for (i=0; i<4; i++) {
	this["btn"+i].onRelease = function() {
		trace("this"+*);
	};
}

each button traces “this4”

this example does work!


for (i=0; i<4; i++) { 
        myBtn = this["mybtn"+i]; 
        myBtn.num = i; 
        myBtn.onRelease = function() { 
            trace(this.num); 
        }; 
    }

each button traces properly.

what I want to know is why, I’m happy that I got this code to work at all, but I would really like to know why the bottom one works, and the top doesn’t, so I at least learn from this.
My guess is that it has to do with the incrementing variable (“i”) inside the for loop, but I just want to be clear on this.

thanks

in the first one, you are tracing the value of i when the button is clicked. By the time you click the button, that for loop has already finished up. At the end of that loop (thanks to the i++) that variable i’s value has made it to 4. tracing i will trace 4. Since each one of those buttons is tracing i, they’re all tracing 4.

The second version you assigned a new variable to be the value of i at that time. when you assign num to = i, it equals i at that time of assignment meaning it will be that and stay that and relate to the number associated with the button.

What you should walk away with this is that variables are not “burnt” into functions when they are placed there. They will reflect the variable, where ever it may exist at the time it was requested, not at the time the function using that variable was defined. For example…

count = 0;
function increaseCount(){
    count++;
}

Wouldnt you expect that function to always use count with its value at the time the function was called and not when it was defined (thereby making count always 0)? The for loop thing is a little less apparent, but its the same concept. The second version you have is the correct way to counter this behavior.

What you should walk away with this is that variables are not “burnt” into functions when they are placed there. They will reflect the variable, where ever it may exist at the time it was requested, not at the time the function using that variable was defined.

Exactly what I needed to read. thank you!

welcome :wink: