Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a frequently asked question but I will try to give a better explanation than I have found. When you pass a function as a parameter (as when defining your event handler), javascript does not evaluate the function at that time, but instead stores the function along with a reference to its parent <code>scope</code>.</p> <p>The function does not get evaluated until the event handler is triggered. At that time, the interpreter will check the value of <code>sub</code> in the parent <code>scope</code>. Since this will always happen after your <code>for</code> loop has completed, it will always find the last value of <code>sub</code>, i.e. whatever <code>sub</code> was when your <code>for</code> loop was completed. So all of your event listeners will use the last value of <code>sub</code>.</p> <p>We can get the desired behavior by creating a <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures?redirectlocale=en-US&amp;redirectslug=Core_JavaScript_1.5_Guide%2FClosures" rel="nofollow">closure</a>. Replace this:</p> <pre><code>supcont.addEventListener("click",function() { toggleVisibility(sub); }); </code></pre> <p>with this:</p> <pre><code>(function(localSub) { supcont.addEventListener("click",function() { toggleVisibility(localSub); }); })(sub); </code></pre> <p>The reason this works is because we wrap each event handler declaration with a new parent <code>scope</code> by invoking an IIFE. This forces the event handler to retain a copy of the <code>scope</code> inside the IIFE (called creating a closure over that <code>scope</code>). Now, when the event handler goes looking for <code>localSub</code>, it will find it in the new parent <code>scope</code> and it will have the value we want.</p>
    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. This table or related slice is empty.
    1. 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