Javascript: why does jQuery do this: (function(){ ...});, and how does it work?
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 exe开发者_高级运维cute 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");
})();
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 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);
(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...
精彩评论