Creating closures within a for loop - am I doing this right?
<p>I am prob. being pretty dense here but I can't figure out exactly what is going on in the code below.</p>

<p>What I am trying to do is attach two, separate, handlers to the change event of a field. Each handler is set up by looping over an array and using the items in the array to effect the output of the handler when it runs - hopefully will become clear when you look at the example code.</p>

<p>Code follows:</p>

<pre><code>    $(document).ready( function () {
        //
        // Create some test input fields on the page...
        //
        $('&lt;br /&gt;').insertAfter($('body &gt; *:last'));
        $('&lt;input type="text" name="t0" id="t0" value="" /&gt;').insertAfter($('body &gt; *:last'));
        $('&lt;input type="text" name="t1" id="t1" value="" /&gt;').insertAfter($('body &gt; *:last'));

        //
        // The problematic part  - for me at least...
        //
        var arr = new Array(1, 2);
        for (var a in arr) {
            // Using Chrome console here for logging
            console.log("## " + a);
            $('#t0').change(function () {
                console.log("&gt;&gt; " + a)
            });
        }
    });
</code></pre>

<p>So what I would expect to happen when I add a value to the first field is, from within the console (running these examples within Chrome):</p>

<pre><code>## 0
## 1
&gt;&gt; 1
&gt;&gt; 2
</code></pre>

<p>What I get is:</p>

<pre><code>## 0
## 1
&gt;&gt; 1
&gt;&gt; 1
</code></pre>

<p>I would have expected the function passed to the handler would form a closure over the value of <code>a</code> and I would end up with two functions being bound to the handler, one in which <code>a</code> had the value <code>1</code> and one in which <code>a</code> had the value <code>2</code>.</p>

<p>Ideas?</p>

<p>Cheers - kris</p>
