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.

mamoo
  • 8,156
  • 2
  • 28
  • 38
anthonytwp
  • 237
  • 1
  • 3
  • 9

4 Answers4

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

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 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. – Jordan Arsenault Apr 12 '12 at 09:53
  • @JordanArsenault yes - I missed one out - thanks! – Alnitak Apr 12 '12 at 09:58
  • Thanks a lot, guys. Your combined comments helped me understand it completely. Cheers.:) – anthonytwp Apr 13 '12 at 03:49
  • 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](http://benalman.com/news/2010/11/immediately-invoked-function-expression/#highlighter_210366) (Immediately Invoked Function Expressions) – Jordan Arsenault Apr 18 '12 at 20:00
  • @JordanArsenault FWIW, there's other ways of fooling the parser into recognising a function expression without enclosing it in parens. – Alnitak Apr 18 '12 at 21:07
2

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

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
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!!

0

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

GillesC
  • 10,647
  • 3
  • 40
  • 55