Merc
Merc

Reputation: 17067

Clarification on closures in Javascript with AJAX

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 :D )

Merc.

Upvotes: 8

Views: 2685

Answers (7)

Pointy
Pointy

Reputation: 413737

You don't need that extra closure in the first example. This'd work fine:

function request(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
      callback(xhr);
  };
  xhr.open('GET', url, true);
  xhr.send('');
}

In modern browsers (or browsers patched with a polyfill) you could also do this:

function request(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = callback.bind(null, xhr);
  xhr.open('GET', url, true);
  xhr.send('');
}

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:

function request(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = callback(xhr);
  xhr.open('GET', url, true);
  xhr.send('');
}

The problem is with the line here:

  xhr.onreadystatechange = callback(xhr);

That assigns to the onreadystatechange the 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.

Upvotes: 9

Merc
Merc

Reputation: 17067

I am answering my own question because the edit would confuse everything -- please excuse me if that's not the way to do it.

So... What I actually meant to write, in my example, is:

function request(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){ callback(xhr); }
  xhr.open('GET', url, true);
  xhr.send('');
}

Or, since I don't need xhr (I can use "this"):

function request(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = callback;
  xhr.open('GET', url, true);
  xhr.send('');
}

So, in the end, I was right... using a closure (as seen in the original question) is a complete waste of time, right?

It would have been important if there was a cycle, and I had to set several callbacks. But in this case, since a new xhr is created every time "request" is invoked, and it's set with the right callback, there is no actual need of having a closure.. right?

Merc.

Upvotes: 0

Raynos
Raynos

Reputation: 169401

You don't need to pass xhr to the callback.

You can just do xhr.onreadystatechange = callback;

and then use this to reference the xhr object inside the callback.

Example:

xhr.onreadystatechange = function () {
  console.log(this.readystate);
};

Disclaimer: For some value of cross browser support >_>

Upvotes: 1

Yola
Yola

Reputation: 19043

In C, and most other common languages after a function returns, all the local variables are no longer accessable because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, then the local variables can remain accessable after returning from the function you called.

Upvotes: 1

Dan
Dan

Reputation: 10786

Good question. There's an important difference between a function call and a pointer to a function - you want to give them a pointer to a function (not really, it's a closure, but that's what I'm calling it) so that they can call it later on. This is really important if you ever do functional programming, or play with anything in the Lisp family.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

In the code you show you're actually calling callback because of the () at the end.

Upvotes: 1

SLaks
SLaks

Reputation: 887459

When you write xhr.onreadystatechange = callback(xhr), you're calling callback immediately and assigning its result to onreadystatechange.

Upvotes: 6

Related Questions