Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You don't need that extra closure in the first example. This'd work fine:</p> <pre><code>function request(url, callback){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ callback(xhr); }; xhr.open('GET', url, true); xhr.send(''); } </code></pre> <p>In modern browsers (or browsers <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow">patched with a polyfill</a>) you could also do this:</p> <pre><code>function request(url, callback){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = callback.bind(null, xhr); xhr.open('GET', url, true); xhr.send(''); } </code></pre> <p><em>edit</em> &mdash; also take note of the answer @Raynos provided. You don't really need to pass the XHR object as a parameter.</p> <p><em>edit again</em> &mdash; in response to a legit comment, you asked why your original idea wouldn't work:</p> <pre><code>function request(url, callback){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = callback(xhr); xhr.open('GET', url, true); xhr.send(''); } </code></pre> <p>The problem is with the line here:</p> <pre><code> xhr.onreadystatechange = callback(xhr); </code></pre> <p>That assigns to the <code>onreadystatechange</code> the value <em>returned</em> from a <em>call</em> to the callback function right then and there. In other words, instead of establishing something to be called when the state changes, the call is made immediately. That error is really common, because it's easy to read it incorrectly. Any time, however, JavaScript sees a function reference followed by a parenthesized argument list, that's interpreted as a request to perform the function call, and not a request for a function wrapper around a future function call.</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. 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