Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (function() mean in this particular code segment? [duplicate]

I'm (re)learning Ajax from the Mozilla site on https://developer.mozilla.org/en/AJAX/Getting_Started, and I'm faced with this segment of code:

(function () {
    var httpRequest;
    document.getElementById("ajaxButton").onclick = function () {
        makeRequest('test.html');
    };

    function makeRequest(url) {
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = alertContents;
        httpRequest.open('GET', url);
        httpRequest.send();
    }

    function alertContents() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                alert(httpRequest.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }
    }
} //missing closing bracket added by bwalton 5/11/11.   )();

While I managed to understand the code and get it working, it's not until I stripped off the "(function() {" part at the top and all the end braces at the end of this code segment. The thing is I don't understand the purpose of" (function{", and it seems neither does FF. (It doesn't recognize this segment as Javascript until I stripped off the "(function{" portions. Does anyone know the purpose of this segment of code? I knew I've seen it somewhere as well, and this time I want to know exactly what it means.

Thanks in advance for your help.

like image 901
anthonytwp Avatar asked Jul 02 '26 18:07

anthonytwp


1 Answers

This:

(function() {
    ...
})();

creates a function and calls it immediately, with its own scope. A common term for this is an IIFE - "immediately invoked function expression".

In this case, you've inadvertently combined the last two lines, so the single line comment mentioning bwalton has broken the code by removing the trailing ) ();.

Without the trailing () you have a function reference, but it's not invoked.

All you need to do to fix your copy of the code is add a carriage return after bwalton 5/11/11..

like image 164
Alnitak Avatar answered Jul 04 '26 06:07

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!