Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
Merc Avatar asked Oct 30 '11 15:10

Merc


People also ask

How to explain closure JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What is difference between closure and lexical scope?

The lexical scope allows a function scope to access statically the variables from the outer scopes. Finally, a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.

Why do we need closures in JavaScript?

In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.

Is closure functional?

The term closure is often used as a synonym for anonymous function, though strictly, an anonymous function is a function literal without a name, while a closure is an instance of a function, a value, whose non-local variables have been bound either to values or to storage locations (depending on the language; see the ...


3 Answers

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.

like image 166
Pointy Avatar answered Nov 09 '22 07:11

Pointy


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

like image 36
SLaks Avatar answered Nov 09 '22 05:11

SLaks


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

like image 24
Dave Newton Avatar answered Nov 09 '22 07:11

Dave Newton