I am supposed to have understood Cloures properly in Javascript, but I obviously didn’t…
At the moment, the text I am reading has this function to abstract an AJAX call:
function request(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (function(myxhr){
return function(){
callback(myxhr);
}
})(xhr);
xhr.open('GET', url, true);
xhr.send('');
}
Here is my actual problem: my brain is refusing to understand why this one wouldn’t work:
function request(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = callback(xhr);
xhr.open('GET', url, true);
xhr.send('');
}
I mean, in “my” way, what I imagine would happen is that I call say request(‘http://…’, a_callback). Within request(), a new xhr object is created, and it’s assigned to the callback… would wouldn’t it work? What would the (nasty) side effects be? From my (limited) understanding, you need closures when for example in a cycle you might end up referring to the latest value of a function variable. But here… doesn’t that “var xhr=…” make sure that a new object is created every time?
Please explain as if I had an IQ of 30 (which is probably true 😀 )
Merc.
You don’t need that extra closure in the first example. This’d work fine:
In modern browsers (or browsers patched with a polyfill) you could also do this:
edit — also take note of the answer @Raynos provided. You don’t really need to pass the XHR object as a parameter.
edit again — in response to a legit comment, you asked why your original idea wouldn’t work:
The problem is with the line here:
That assigns to the
onreadystatechangethe value returned from a call 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.