Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>With the code you have provided <code>test</code> will still be in scope inside the callback. <code>xhr</code> will not be, other than <code>xhr.responseText</code> being passed in as <code>data</code>.</p> <p><strong>Updated from comment</strong>:</p> <p>Assuming your code looks something like this:</p> <pre><code>for (var test in testers) getFileContents("hello"+test+".js", function(data) { alert(test); }); } </code></pre> <p>As this script runs, <code>test</code> will be assigned the values of the keys in <code>testers</code> - <code>getFileContents</code> is called each time, which starts a request in the background. As the request finishes, it calls the callback. <code>test</code> is going to contain the <strong>FINAL VALUE</strong> from the loop, as that loop has already finished executing. </p> <p>There is a technique you can use called a closure that will fix this sort of problem. You can create a function that returns your callback function, creating a new scope you can hold onto your variables with:</p> <pre><code>for (var test in testers) { getFileContents("hello"+test+".js", (function(test) { // lets create a function who has a single argument "test" // inside this function test will refer to the functions argument return function(data) { // test still refers to the closure functions argument alert(test); }; })(test) // immediately call the closure with the current value of test ); } </code></pre> <p>This will basically create a new scope (along with our new function) that will "hold on" to the value of <code>test</code>. </p> <p>Another way of writing the same sort of thing:</p> <pre><code>for (var test in testers) { (function(test) { // lets create a function who has a single argument "test" // inside this function test will refer to the functions argument // not the var test from the loop above getFileContents("hello"+test+".js", function(data) { // test still refers to the closure functions argument alert(test); }); })(test); // immediately call the closure with the value of `test` from `testers` } </code></pre>
    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. 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.
 

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