title: How to structure javascript callback so that function scope is maintained properly
body: <p>I'm using XMLHttpRequest, and I want to access a local variable in the success callback function.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>function getFileContents(filePath, callbackFn) {  
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
          if (xhr.readyState == 4) {
              callbackFn(xhr.responseText);
          }
      }
      xhr.open("GET", chrome.extension.getURL(filePath), true);
      xhr.send();
  }
  </code></pre>
  
  <p>And I want to call it like this:</p>
  
  <pre><code>var test = "lol";
  
  getFileContents("hello.js", function(data) {
      alert(test);
  });
  </code></pre>
  
  <p>Here, <code>test</code> would be out of the scope of the callback function, since only the enclosing function's variables are accessible inside the callback function. What is the best way to pass <code>test</code> to the callback function so the <code>alert(test);</code> will display <code>test</code> correctly?</p>
  
  <p>Edit:  </p>
  
  <p>Now, if I have the following code calling the function defined above:</p>
  
  <pre><code>for (var test in testers) {
      getFileContents("hello.js", function(data) {
          alert(test);
      });
  }
  </code></pre>
  
  <p>The <code>alert(test);</code> code only prints the last value of <code>test</code> from the <code>for</code> loop. How do I make it so that it prints the value of <code>test</code> during the time at which the function <code>getFileContents</code> was called? (I would like to do this without changing <code>getFileContents</code> because it's a very general helper function and I don't want to make it specific by passing a specific variable like <code>test</code> to it.</p>