Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you create a function that refers to variables outside of it, these references will be resolved at the time you call this function.</p> <p>In your case:</p> <pre><code>var functions = []; function outer() { for (var i = 0; i &lt; N; i++) { // &lt;------------ functions[i] = function() { // | alert(i); // &lt;-- this 'i' refers to this one } } // At the end of the for loop, i == N (or N+1?) } functions[x](); // Will show N (or N+1) // because that's the current value of i in the outer function // (which is kept alive just because something refers to it) </code></pre> <p>What you want to do is capture the value of 'i' at each step of the loop, for later evaluation, e.g.:</p> <pre><code>var functions = []; function outer() { for (var i = 0; i &lt; N; i++) { // &lt;--------------------------------------- functions[i] = (function(my_i) { // &lt;---- | return function () { // | | alert(my_i); // my_i refers to this which is a copy of 'i' there } }(i)); // run function(with my_i = the i at each step of the loop) } } functions[x](); // Will show x </code></pre> <p>You can see there is an inner function that gets a copy of the current counter as a parameter. This inner function stays alive with that copy, so that later calls to the stored innest function returns the value of the my_i of the function that created it -- Clear? :-)</p> <p>This is the wonderful world of closures. It may take a bit of mind-bending to first get it, but then you'll be glad you did, so go and google "javascript closures" to death!</p>
    singulars
    1. This table or related slice is empty.
    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. 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.
    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