Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you assign the function to the click handler, a <a href="http://www.jibbering.com/faq/faq_notes/closures.html" rel="noreferrer">closure</a> is created.</p> <p>Basically a closure is formed when you nest functions, inner functions can refer to the variables present in their outer enclosing functions even after their parent functions have already executed.</p> <p>At the time that the click event is executed, the handler refers to the last value that the <code>i</code> variable had, because that variable is stored on the closure.</p> <p>As you noticed, by wrapping the click handler function in order to accept the <code>i</code> variable as an argument, and returning another function (basically create another closure) it works as you expect:</p> <pre><code>for ( var i = 0; i &lt; 4; i++ ) { var a = document.createElement( "a" ); a.onclick = (function(j) { // a closure is created return function () { alert(j); } }(i)); document.getElementById( "foo" ).appendChild( a ); } </code></pre> <p>When you iterate, actually create 4 functions, each function store a reference to <code>i</code> at the time it was created (by passing <code>i</code>), this value is stored on the outer closure and the inner function is executed when the click event fires.</p> <p>I use the following snippet to explain closures (and a very basic concept of <a href="http://en.wikipedia.org/wiki/Curry_(programming)" rel="noreferrer">curry</a>), I think that a simple example can make easier to get the concept:</p> <pre><code>// a function that generates functions to add two numbers function addGenerator (x) { // closure that stores the first number return function (y){ // make the addition return x + y; }; } var plusOne = addGenerator(1), // create two number adding functions addFive = addGenerator(5); alert(addFive(10)); // 15 alert(plusOne(10)); // 11 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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