admin管理员组

文章数量:1321829

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");
})();

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");
})();
Share Improve this question edited Dec 17, 2009 at 23:42 Cheeso asked Dec 17, 2009 at 23:21 CheesoCheeso 193k105 gold badges485 silver badges734 bronze badges 7
  • 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 Commented Dec 17, 2009 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 Commented Dec 17, 2009 at 23:24
  • The source for that code: jquery-1.3.2.js . code.google./p/jqueryjs/downloads/… – Cheeso Commented Dec 17, 2009 at 23:26
  • I agree with brianreavis. Perhaps the developer used an unnamed, uncalled closure to purposely "ment" out the code. Using a multi-line ment around the whole thing would probably conflict with other contained multi-line ments. – brianpeiris Commented Dec 17, 2009 at 23:28
  • Erm, you're saying that jQuery 1.3.2 source code does this? What line numbers? – brianpeiris Commented Dec 17, 2009 at 23:30
 |  Show 2 more ments

8 Answers 8

Reset to default 7

The very last line of the jQuery source is

})();

The parentheses mean that the function is being called.

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

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

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

A mon 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);
(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.

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?

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.

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

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

本文标签: Javascript why does jQuery do this (function() )and how does it workStack Overflow