2

Looking at the fallowing structure of an older jQuery version:

(function( window, undefined ) {

    var jQuery = (function() {

        var jQuery = function( selector, context ) {
            return new jQuery.fn.init( selector, context );
        };

        jQuery.fn = jQuery.prototype = {
            init: function( selector, context ) {
                // ...
                return this;
            }
            // jQuery API methods
        }

        // Give the init function the jQuery prototype for later instantiation
        jQuery.fn.init.prototype = jQuery.fn;

        return (window.jQuery = window.$ = jQuery);

    })();

})(window);

it is quite easy to understand that:

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        return this;
    }
}
jQuery.fn.init.prototype = jQuery.fn;

is the one section that fires when jQuery is called with normal usage as for example

$('p')

or

jQuery('p')

it is really not clear how is it possible to call API methods with the form $.ajax() or $.isArray() and where would you place, lets say, a custom method within the listed code and call it with $.myCustomMethod(). Any help will be very much appreciated.

wiredolphin
  • 1,431
  • 1
  • 18
  • 26

1 Answers1

7

You can write yourself a function:

function something(n) {
  return n + 1;
}

and call it:

var x = something(0);

You can also attach properties to the function, because it's an object:

something.else = function(n) {
  return n - 1;
};

You can then call that function via the property reference:

var y = something.else(0);

The jQuery library uses the global jQuery object (usually referred to as $) as a place to put a collection of functions that are generally useful but which don't have any implicit relationship to a collection of elements or objects the what that the various jQuery "methods" do. An obvious example is $.ajax(), which is super-useful but which really doesn't have anything to do with the DOM.

By keeping all those functions as properties of $, the library avoids "polluting" the global address space.

Pointy
  • 405,095
  • 59
  • 585
  • 614