Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>change:</p> <pre><code>newdiv.ondblclick = function() {alert(items[i])} </code></pre> <p>to this:</p> <pre><code>newdiv.ondblclick = (function(item) { return function() {alert(item)} })(items[i]) </code></pre> <p>Look up <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="nofollow">Closures</a>, which is what is screwing you up in this case. When you create an anonymous function using <code>function() { }</code>, you are creating a closure that is bound in the scope that it was created. So inside your closure, your variable <code>i</code> is the same variable that you were using in the loop. So when you double click on an item, the loop is already finished and <code>i == 12</code>. It would be the same as if you put an <code>alert(i);</code> directly after your <code>for(i in items) { }</code> loop.</p> <p>So, with that in mind, how does my second example fix that? </p> <p>Well, it uses a self-executing anonymous function that accepts one variable, <code>item</code>. This function returns a closure, which is bound inside <em>its</em> scope. The outer closure is immediately executed, passing in <code>items[i]</code>, which creates a stable scope for the variable that you want to live in.</p> <p>Closures can be a little mind bending if you aren't used to them, but understanding them is a big part to getting functional programming using JavaScript.</p> <p>SetAttribute works because you are creating a new string that evaluates each time through the loop, rather than late-referencing the variable <code>i</code>.</p> <p><em>PS</em></p> <p>Its probably a bad idea to use a <code>for( in ) {}</code> on an array. You might get unexpected results, it should loop through all the propertys of the object not just the items in the array. its probably safer to use a regular <code>for(var i=0;i&lt;items.length;i++) {}</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload