Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a bazillion answers to this exact same question here on stackoverflow, i'll hunt some down in a minute, but here are the key points:</p> <ul> <li>Javascript has lexical scope (not dynamic scoping)</li> <li>The smallest Javascript scope in javascript is a <code>function</code></li> <li>Block <em>do not</em> have thier own scope</li> <li>Javascript uses variable hoisting, which means all variables in a scope are found before the scope executes and moved to the beginning of the scope. Which means that <code>var image = ...</code> isn't where you think it is. There is only one <code>image</code> variable, which (due to lexical scoping) is the variable you are accessing in your closure, which at the conclusion of the loop will obviously point at the last iterated item.</li> <li>Functions are first-class objects, which means they are treated like variables and can be assigned and passed around as such</li> <li>you can create a stable scope for a variable to live in by creating a self-executing anonymous function</li> </ul> <p>So for example:</p> <pre><code>(function(localImage) { image.addEventListener ('click',function() {showId(localImage.id);},false); })(image); </code></pre> <p>Also, as others have pointed out, event listener closures are executed in the <em>context</em> that they were bound. So conversely, without having worry about using a close to fix a scope, you could do:</p> <pre><code>image.addEventListener ('click',function() {showId(this.id);},false); </code></pre> <p><em>Edit</em></p> <p>Some links to similar questions and some different perspectives on the answer:</p> <ul> <li><a href="https://stackoverflow.com/questions/2095902/accessing-loop-iteration-in-a-sub-function">Accessing loop iteration in a sub-function?</a></li> <li><a href="https://stackoverflow.com/questions/4418326/closures-in-a-for-loop-and-lexical-environment">Closures in a for loop and lexical environment</a></li> <li><a href="https://stackoverflow.com/questions/3150010/strange-things-in-javascript-for">Strange things in JavaScript “for”</a></li> <li><a href="https://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure">Event handlers inside a Javascript loop - need a closure?</a></li> </ul> <p>I could go on but a bazillion is a big number...</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