Question

enter image description here

I'm trying to learn ajax from online tutorial, but i don't understand on line 20, why doesn't handleServiceResponse function have parentheses()? and why won't it work with parentheses?

Thanks so much, you guys here are the best.

Était-ce utile?

La solution

xmlHttp.onreadystatechange = handleServerResponse;
function handleServerResponse() {
   ...
}

is the same as:

xmlHttp.onreadystatechange = function() {
   ...
}

In this case, onreadystatechange expects to be set as a function definition.


To demonstrate a usage where you could use parentheses here, here is an example:

xmlHttp.onreadystatechange = generateServerResponseHandler();
function generateServerResponseHandler() {
    return function() {
        ...
    };
}

You can see that the function generateServerResponseHandler is called immediately, but onreadystatechange is still set to a function definition.


In JavaScript, functions are "first class citizens". Wikipedia has an excellent writeup: http://en.m.wikipedia.org/wiki/First-class_function

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top