2

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.

0

4 Answers 4

7

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..

Sign up to request clarification or add additional context in comments.

4 Comments

You're one parenthesis short, aren't you? It's worth noting that the initial opening parenthesis and it's closing pair can be left out, but serve as a convention (as a visual indicator) that this function will be immediately invoked. They are not required. However, the (); at the end is definitely required for invocation.
Thanks a lot, guys. Your combined comments helped me understand it completely. Cheers.:)
To clarify my last comment -- in the context of the above answer, the external parens are actually required, or the javascript parser will throw an error. The parser makes distinctions between function declarations and function expressions. The external parens are not required for expressions, for instance var i = function(){ return 10; }(); but are required for declarations, as above. See Ben Alman's article on IIFE's (Immediately Invoked Function Expressions)
@JordanArsenault FWIW, there's other ways of fooling the parser into recognising a function expression without enclosing it in parens.
2

(function() { /* code here */ })(); creates an anonymous function and executes it in place. One of the purposes is to create a local scope.

Comments

0

Do u see that ()();

that is a call parenthesis attached to some value. Now.

(function(){});

is a function, an anonymous function closed under the parenthesis. Adding it all up.

(function(){}) ();

a call to a function enclosed in parenthesis. Amazing!!

Comments

0

As explained above this is a closure, see the links for more information about closures http://jibbering.com/faq/notes/closures/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.