AJAX - The Complete Reference

(avery) #1

Chapter 3: XMLHttpRequest Object 111


PART I


x = "Late to the party!";

}
outer();

It might be surprising to you, since the timeout and the reassignment happens after the
function is defined, that the value of x is the string value “Late to the party!” as shown here.
This shows that the inner function is not just copying the value of the variable x but also
holds a reference to that variable.

Do not assume that closures are related solely to timeouts and other asynchronous
activity such as what Ajax thrives on. The following little example shows you could just as
easily use them when doing high-order JavaScript programming when you return functions
as values for later use:

function outer()
{
var x = 10;
var inner = function() { alert(x); }
x = "Late to the party!";
return inner;
}
var alertfunction = outer();
alertfunction();

You have seen closures throughout this chapter. Every time we make an XHR, we assign
a function to be called back upon a readyState value change and we want to capture the
local variable associated with the created XHR for reference.

function sendRequest(url,payload)
{
var xhr = createXHR();
if (xhr)
{
xhr.open("GET",url + "?" + payload,true);
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
}
}

Note that the variable xhr is local to the function sendRequest but through the closure
it is made available to the handleResponse callback function.
Beyond such a rudimentary example of closures, you will also encounter such constructs
all over typical Ajax applications because of the need of setting up various event handlers to
address user activity in a richer user interface. This is where the trouble begins.
Free download pdf