javascript closure example
<p>I was reading this website for notes on closure:  blog.morrisjohns.com/javascript_closures_for_dummies.html</p>

<p>It had the following example:</p>

<pre><code>function buildList(list) {
  var result = [];
  for (var i = 0; i &lt; list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  // using j only to help prevent confusion - could use i
  for (var j = 0; j &lt; fnlist.length; j++) {
    fnlist[j]();
  }
}
</code></pre>

<p>Their notes (correctly) point out:</p>

<blockquote>
  <p>The line result.push( function()
  {alert(item + ' ' + list[i])} adds a
  reference to an anonymous function
  three times to the result array. If
  you are not so familiar with anonymous
  functions think of it like:
      pointer = function() {alert(item + ' ' + list[i])};
      result.push(pointer);</p>
  
  <p>Note that when you run the example,
  "item3 undefined" is alerted three
  times! This is because just like
  previous examples, there is only one
  closure for the local variables for
  buildList. When the anonymous
  functions are called on the line
  fnlistj; they all use the same
  single closure, and they use the
  current value for i and item within
  that one closure (where i has a value
  of 3 because the loop had completed,
  and item has a value of 'item3').</p>
</blockquote>

<p>Is there a "correct" way to get the "expected" behavior in javascript? </p>

<p>Thanks!</p>
