Sunday, December 20, 2009

Anonymous functions and its usage in Javascript

Everybody knows there exists anonymous classes, but not anonymous functions.

There exists anonymous functions only in Javascript. C,C++,Java doesnot like that.
It is widely used in python,ruby,c#,Lisp,PHP...

Anonymous function doesnt have name to it.
Example.

function square(x)
{
return x*x;
}

var a = (function(x) { return x*x;})(10); //100;

Which scenario it can used
--------------------------

var request;

function init()
{
var url = 'http://ajax.googleapis.com/ajax/services/search/local?hl=en&v=1.0&rsz=large&q=pubs paris &start=0';
sendRequest(url);
url='http://www.google.com';
sendRequest(url);
}
function sendRequest(addr) {
request = new XMLHttpRequest();
request.onreadystatechange = handleResponse;
request.open("GET", addr, true);
request.send(null);
}

function handleResponse() {
if (request.readyState == 4) {
alert(request.responseText);
}
}

sendRequest() is called for two URL next to next.. Whichevers request, is served first, then global variable 'request' is updated with that response. So when the second request's response comes then it cannot take its proper value.
If u run the above snippet, u would see alert() is called only once.

url='http://www.google.com';
sendRequest(url); ----> Change this line to setTimeout("sendRequest('http://www.google.com')",3000);

No issue will be seen. This is a race condition.

Changed code :

function init()
{
var url = 'http://ajax.googleapis.com/ajax/services/search/local?hl=en&v=1.0&rsz=large&q=pubs paris &start=0';
sendRequest(url);
url='http://www.google.com';
sendRequest(url);
}

function sendRequest(addr) {

var request = new XMLHttpRequest();
request.onreadystatechange = function(){

if (request.readyState == 4) {
alert(request.responseText);
}
};
request.open("GET", addr, true);
request.send(null);
}


Make the 'request' variable local to senrequest() and introduce anonymous functions to handle the response for each request. So that a local copy of 'request' will be given to function and when the response comes each call will have its own copy.So no clash.

No comments:

Post a Comment