Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have a classic closure problem in these two places:</p> <pre><code>bar.onclick = function () { mod_row('add', s) }; //... bar.onclick = function () { mod_row('del', s) }; </code></pre> <p>The problem is that the <code>s</code> inside those two functions refers to the <code>s</code> in the outside scope so when the click handlers are called, they'll end up using whatever value <code>s</code> had when the outer scope was finished. You need to force that <code>s</code> to be evaluated when you generate your click handler functions. The usual approach is to use a function to generate your callback functions:</p> <pre><code>bar.onclick = (function(inner_s) { return function() { mod_row('add', inner_s); } })(s); //... bar.onclick = (function(inner_s) { return function() { mod_row('del', inner_s); } })(s); </code></pre> <p>That extra layer of function evaluation forces <code>s</code> to be evaluated (as <code>inner_s</code>) when you assign to <code>bar.onclick</code> rather than when <code>bar.onclick</code> gets called.</p> <p>You can't get away from dealing with pointers even in languages that claim not to have them.</p> <p><strong>UPDATE</strong>: Here's a clarification of how the funky self-executing functions work. This:</p> <pre><code>bar.onclick = (function(inner_s) { return function() { mod_row('add', inner_s); } })(s); </code></pre> <p>is functionally equivalent to this:</p> <pre><code>function closure_hack(inner_s) { return function() { mod_row('add', inner_s); } } bar.onclick = closure_hack(s); </code></pre> <p>When <code>closure_hack</code> is called, it is given <code>s</code> and <code>s</code> is a reference to a certain object. Then, inside <code>closure_hack</code>, <code>inner_s</code> refers to the same object that <code>s</code> refers to. Outside of <code>closure_hack</code>, <code>s</code> can change to <strong>refer to a different object</strong> but the <code>inner_s</code> still refers to the old one. The function call &mdash; either through <code>closure_hack</code> or the idiomatic self-executing function &mdash; is just a way to divorce the variable name, <code>s</code>, from the object it refers to: the goal is to grab a hold of what <code>s</code> refers to so that <code>s</code> can change without undesirable side effects.</p> <p>This is tricky stuff and takes some getting used to. Closures trip everyone up, don't feel bad about being a bit confused.</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