Javascript unwanted closure behavior
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example">Javascript closure inside loops - simple practical example</a>  </p>
</blockquote>



<p>I was trying to code something similar to this :</p>

<pre><code>var funcs = [];
for (var i=0; i&lt;5 ; ++i) {
    funcs[i]=function() {
        alert(i);
    };
}
</code></pre>

<p>Obviously, calling <code>funcs[0]</code> won't alert <code>0</code> as expected, simply because the variable <code>i</code> is captured by the anonymous function, and calling any of <code>funcs[0..4]</code> will alert '4' (the value of <code>i</code> after the last iteration and shared by all created functions).</p>

<p>The first work around that comes to my mind is using some kind of function generator :</p>

<pre><code>var funcs = [];
for (var i=0; i&lt;5 ; ++i) {
    funcs[i]=(function(cap) {
        return function() {alert(cap)};
    })(i);
}
</code></pre>

<p>This do the trick, but seems really puzzling and hard to read.  Is there any better way to get the intended behavior without using a function wrapper?</p>
