views:

240

answers:

8

EDIT: I THOUGHT The jQuery source I was looking at did something like this:

(function(){
    var bunchOfVariables = 7;
    jQuery = " ....."; 
    //....
});

I was wrong about that. Ignore this question.


I don't understand what that does. Can someone please explain it?

This is the very first line in jQuery-1.3.2.js.

It appears to define an anonymous function, and NOT execute it. Where does the function go? How does it get run?

If I use code like that in a test script, it never gets called. On the other hand, if I follow it with open-close paren, then it gets called :

// never gets called
(function(){
    say("hello");
});
// gets called
(function(){
    say("buon giorno");
})();
+2  A: 

It's a closure to avoid leaking global symbols. You define a function and immediately execute it.

(function(){
  // some code
})();

A common version of this pattern explicitly binds the '$' symbol to jQuery, in case jQuery.noConflict() was called:

(function($){
  // some code here, '$' is bound to jQuery
})(jQuery);
orip
A: 
(function(){
var bunchOfVariables = 7;
jQuery = " ....."; 
//....
});

is actually creating a new anonymous function without parameters with some variable in it. But you are only create an instance not calling the function itself.

Imagine you want to store a function into a var you will do:

var fn=function(parameter1, parameter2){..}

fn is now holding an instance of the anonymous function, to call it you have to do

fn(arg1, arg2).

So with your open close paren you are just calling the function but without any arguments.

Patrick
Just to clarify - the first code block in your answer is equivalent, in effect, to commented-out code. The body of the function is *not* being executed.
brianpeiris
+2  A: 
(function() { /* ... */ })();

This pattern is usually referred to as a 'self-executing anonymous function'. It defines a new anonymous function (that's the function() { /* ... */ } part) and immediately executes it (that's the () at the end). The extra parentheses around the function declaration aren't strictly necessary, but help make the code clearer.

Now why would anyone want to do this? Each function in JavaScript has its own scope. Any variables or functions declared within it are local to the function and only accessible within it. So let's say you're writing a jQuery plugin. Maybe you need lots of variables and internal methods for your plugin. If you declare all of this in a self-executing anonymous function, you avoid polluting the global scope with all your internal objects.

Annabelle
+7  A: 

The very last line of the jQuery source is

})();

The parentheses mean that the function is being called.

brianpeiris
My bad - my paren-matching was off in the editor, and somehow I thought it was the former, when it was not.
Cheeso
+3  A: 

What it's actually doing is:

(function(){
    var bunchOfVariables = 7;
    jQuery = window.jQuery = window.$ = ...
    //....
})();

Note the '()' at the end, which runs that whole block of code. The reason for this is to keep all of those 'bunchOfVariables' from ending up in the 'global' (read: window) scope.

jQuery (and $), however, ends up being available globally because of the line:

jQuery = window.jQuery = window.$ = ...

Remember, in the DOM world, 'global' means 'member variable of window'.

Chris Waters
Ahh, Somehow my editor wasn't matching up the curlies and parens quite right. I had thought the matching close-curly for the first line was not immediately followed by )(); .
Cheeso
+1  A: 

I think you might be mistaken. The first line of the jQuery starts a self-executing anonymous function. Are you sure you didn't match the braces incorrectly?

Brian Fisher
YES, that's exactly what I did. . .
Cheeso
+1  A: 

jQuery 1.3.2 (the current release) defines an anonymous function along those lines, but does execute it; I suspect you're being misled by some...anomalous indentation that they have in the release copy.

The point of the anonymous function is to provide scoping. This is called the "module pattern." Here's a simplified example

(function() {

    function doSomething() {
        doSomethingElse();
    }

    function doSomethingElse() {
    }

    window.doSomething = doSomething;
})();

(Although that's not normally how I would do the module pattern, it's similar to how jQuery does it.)

Now there's a "public" symbol (doSomething, which is a property of window) which references the doSomething function. The doSomethingElse function is accessible from doSomething, but from nowhere else. E.g., it's privately scoped.

T.J. Crowder
My editor, or more accurately, the editing mode, is letting me down. It's getting the paren-match wrong, and that is what led me to beieve the anon function was not being executed. I was wrong of course.
Cheeso
A: 

(function() { /* ... */ }) is not a "self-executing anonymous function", the () is not just "the look of the code", they execute the function...

Dan Beam