Search code examples
javascriptajaxclosuresparenthesesself-invoking-function

Why doesn't Ajax use self-invocation?


The weird syntax of a self-invoking closure function implies that you are essentially calling the function itself, hence making it self-invoking. Here is some code demonstrating this:

<!DOCTYPE html>
<html>
    <head>
        <title>
            A Nameless Function that Executes Itself
        </title>
    </head>

    <body onload = "mainMethod();">

        <div id = "here"></div>

        <script type = "text/javascript">

            function mainMethod()
            {
                var here = document.getElementById("here");
                var hello = "Hello World!";

                here.innerHTML = function()
                {
                    return hello + "<br />";
                }(); // WITH method parentheses -- self-invoking

                here.innerHTML += function()
                {
                    return hello;
                }; // withOUT method parentheses
            }
        </script>
    </body>
</html>


...the second function above does not execute because it lacks the ending parentheses, and the innerHTML becomes the entire function itself. So, why doesn't your standard Ajax syntax use self-invocation in the same way? It would seem that the XMLHttpRequest processes the onreadystatechange attribute in a unique way. Here is an example:

function getStock()
{
    var req = new XMLHttpRequest();

    var stock = document.getElementById("stock");

    req.onreadystatechange = function()
    {
        if( (req.readyState == 4) && (req.status == 200) )
        {
            // value of stock
            var stockValue = req.responseText;

            stock.innerHTML = stockValue;
        }
    }
    req.open("GET", "randomStockValue.php?random=", true);
    req.send(null);

    setTimeout("getStock()", 1000);
}


Notice the lack of ending parentheses... I'm asking this because I want to further understand Ajax syntax, and what exactly it is doing.


Solution

  • It registers an event listener. The function does not get executed instantly, it (the Function object) is just assigned to the onreadystatechange property. It will be invoked some later time - when the ajax request changes its state. It's something like a setTimeout with an unknown timeout (and it will be invoked more than one time).