title: How to copy a variable in JavaScript?
body: <p>I have this JavaScript code:</p>
  
  <pre><code>for (var idx in data) {
      var row = $("&lt;tr&gt;&lt;/tr&gt;");
      row.click(function() { alert(idx); });
      table.append(row);
  }
  </code></pre>
  
  <p>So I'm looking through an array, dynamically creating rows (the part where I create the cells is omitted as it's not important). Important is that I create a new function which encloses the idx variable.</p>
  
  <p>However, idx is only a reference, so at the end of the loop, all rows have the same function and all alert the same value.</p>
  
  <p>One way I solve this at the moment is by doing this:</p>
  
  <pre><code>function GetRowClickFunction(idx){
      return function() { alert(idx); }
  }
  </code></pre>
  
  <p>and in the calling code I call</p>
  
  <pre><code>row.click(GetRowClickFunction(idx));
  </code></pre>
  
  <p>This works, but is somewhat ugly. I wonder if there is a better way to just copy the current value of idx inside the loop?</p>
  
  <p>While the problem itself is not jQuery specific (it's related to JavaScript closures/scope), I use jQuery and hence a jQuery-only solution is okay if it works.</p>