1

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");
})();
Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • In your first example, does that get assigned to a variable? If not, I'd assume it's just an unused remnant of the developer. – brianreavis Dec 17 '09 at 23:24
  • If the function doesn't have a name and is not called (i.e. there are no `()` right after the function) then it seems that the code is ignored. Care you mention the source you are looking at? – brianpeiris Dec 17 '09 at 23:24
  • The source for that code: jquery-1.3.2.js . http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.js – Cheeso Dec 17 '09 at 23:26
  • I agree with brianreavis. Perhaps the developer used an unnamed, uncalled closure to purposely "comment" out the code. Using a multi-line comment around the whole thing would probably conflict with other contained multi-line comments. – brianpeiris Dec 17 '09 at 23:28
  • Erm, you're saying that jQuery 1.3.2 source code does this? What line numbers? – brianpeiris Dec 17 '09 at 23:30
  • the last line of jquery.js is `})();`, which means it's executing the function – orip Dec 17 '09 at 23:34
  • Turns out the problem is in emacs/javascript mode, particularly with the unquoted regex's in that file. That broke the paren matching. If I quote the regexes, the paren matching works again. – Cheeso Dec 18 '09 at 01:08

8 Answers8

7

The very last line of the jQuery source is

})();

The parentheses mean that the function is being called.

brianpeiris
  • 10,735
  • 1
  • 31
  • 44
  • My bad - my paren-matching was off in the editor, and somehow I thought it was the former, when it was not. – Cheeso Dec 17 '09 at 23:39
4

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
  • 254
  • 1
  • 2
  • 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 Dec 17 '09 at 23:41
2

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
  • 73,323
  • 21
  • 116
  • 148
2
(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
  • 10,596
  • 5
  • 27
  • 26
  • This is not quite true. You need the "extra parentheses" if you are declaring an anonymous function. If you leave them you will get an error. However, you can ignore them if you assign it to a variable. – Kel Mar 25 '12 at 20:05
1

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
  • 23,519
  • 15
  • 78
  • 82
1

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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 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 Dec 18 '09 at 01:00
0
(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
  • 15,702
  • 1
  • 39
  • 39
  • 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 Dec 17 '09 at 23:39
0

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

Dan Beam
  • 3,632
  • 2
  • 23
  • 27