Function Not Executed When Creating Objects In A Loop - Javascript
In the following code the drawFunc is not executed during the loop (I can see that with a step-by-step-debugging, the code just jumps to the end of the function). The function gets
Solution 1:
You cannot use a variable declared outside a function and assume that its value when used inside that function is what it was at the time the function was declared.
In the particular case of a loop variable, that variable will have the last value assigned to it by the time the inner function is called.
To fix this, you have to "close" the outer variable's value inside a new scope, in your case that would look like this:
for (var i = 0; i < 9; ++i) {
...
drawFunc: (function(i) { // <------------+
return function() { // |alert(i); // you can use this "i" here
}
})(i)
}
The unusual looking construct now there is an immediately invoked function expression which has been passed your loop variable i
, but now has a locally bound copy of that variable in its scope.
Post a Comment for "Function Not Executed When Creating Objects In A Loop - Javascript"