1

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.

  1. What is the outermost unnamed container function? Why is it required?

  2. Why is the container function anonymous?

  3. What is the need for the outermost '(' parantheses ?

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
sonofdelphi
  • 1,986
  • 5
  • 19
  • 25
  • 2
    See this question :) http://stackoverflow.com/questions/2716069/how-does-this-javascript-jquery-syntax-work-function-window-undefined – Nick Craver May 28 '10 at 10:30
  • that question is mostly about the 'undefined' parameter. but there seems to be a few links there... – sonofdelphi May 28 '10 at 10:39
  • ahh, the `undefined`. that is puzzling, isn't it? I'm not sure what it does. Perhaps it is a way to make sure that there is only one item in `arguments`? So that if someone refers to `arguments` it only has the `window` value? Just a guess, so could be totally wrong. – Tauren May 28 '10 at 19:40

2 Answers2

1
  1. The outer function creates a variable scope, IIRC.
  2. The outer parenthesis encapsulate the function. I don't think they're actually required. They just aid understanding
  3. The function is anonymous because it is called immediately:

    (function(w) {...})(window)
    
Eric
  • 95,302
  • 53
  • 242
  • 374
1
  1. The outer parenthesis prevent polluting the global window object.

  2. The container wouldn't have to be anonymous, but there is no reason to name it and pollute the globals.

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

Tauren
  • 26,795
  • 42
  • 131
  • 167