title: How can one de-reference JavaScript variables when enclosing an outer scope
body: <p>Ok, here's a problem script.</p>
  
  <pre><code>var links = [ 'one', 'two', 'three' ];
  
  for( var i = 0; i &lt; links.length; i++ ) {
      var a = document.createElement( 'div' );
      a.innerHTML = links[i];
      a.onclick = function() { alert( i ) }
      document.body.appendChild( a );
  }
  </code></pre>
  
  <p>This script generates three divs: one, two and three, using an array.<br>
  I've set a (Dom0 for simplicity) click handler on each div which alerts the index of its position in the array. - except it doesn't! It always alerts 3, the last index of the array.<br>
  This is because the 'i' in 'alert( i )' is a live reference to the outer scope (in this case global) and its value is 3 at the end of the loop.
  What it needs is a way of de-referencing i within the loop. </p>
  
  <p>This is one solution and I tend to use it. </p>
  
  <pre><code>var links = [ 'one', 'two', 'three' ];
  
  for( var i = 0; i &lt; links.length; i++ ) {
      var a = document.createElement( 'div' );
      a.innerHTML = links[i];
      a.i = i; //set a property of the current element with the current value of i
      a.onclick = function() { alert( this.i ) }
      document.body.appendChild( a );
  }
  </code></pre>
  
  <p>Does anyone else do anything different?<br>
  Is there a really smart way of doing it?<br>
  Does anyone know how the libraries do this?</p>