I was going through the source code of jQuery. I'm having trouble understanding the wrapping strategy for the jQuery object.
(function( window, undefined ) {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
开发者_运维知识库 // The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
....
....
....
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
Specifically, what I'm not able to understand stems from the first line.
What is the outermost unnamed container function? Why is it required?
Why is the container function anonymous?
What is the need for the outermost '(' parantheses ?
- The outer function creates a variable scope, IIRC.
- The outer parenthesis encapsulate the function. I don't think they're actually required. They just aid understanding
The function is anonymous because it is called immediately:
(function(w) {...})(window)
The outer parenthesis prevent polluting the global window object.
The container wouldn't have to be anonymous, but there is no reason to name it and pollute the globals.
The outer parens are required, because it needs to be executed immediately. The
(window)
makes it run immediately, and without the parens, it won't work.
This article is a pretty good read and will probably help you understand.
精彩评论