I was reading this article about how jQuery works , and that article minified jquery structure into symbolic code:
/*1*/ var jQuery = (function ()
/*2*/ {
/*3*/
/*4*/
/*5*/ var jQuery = function (selector, context)
/*6*/ {
/*7*/
/*8*/
/*9*/ return new jQuery.fn.init(selector, context, rootjQuery);
/*10*/ },
/*11*/ rootjQuery;
/*12*/
/*13*/
/*14*/ jQuery.fn = jQuery.prototype = {
/*15*/ constructor: jQuery,
/*16*/ init: function (selector, context, rootjQuery)
/*17*/ {
/*18*/
/*19*/ if (!selector)
/*20*/ {
/*21*/ return this;
/*22*/ }
/*23*/ },
/*24*/ //I screwed with the core!
/*25*/
/*26*/ yo: function ()
/*27*/ {
/*28*/ alert("yo")
/*29*/ },
/*30*/ };
/*31*/
/*32*/ jQuery.fn.init.prototype = jQuery.fn;
/*33*/
/*34*/ // Expose jQuery to the global object
/*35*/ return jQuery;
/*36*/ })();
Line #32 is where the magic happens. so when I'm writing jQuery(..) it actually run new init() which has access to all jQuery.fn functions.
It's pretty clear (most of it) but I have 2 questions :
Question #1 Why does line #15 (constructor: jQuery,) exists ? all it does (imho) is to tell the prototype object that it's ctor function is jQuery. how does jQuery use that fact ?
Question #2 Looking at line #14 , it's obviously adding functions to jQUery.fn ( function yo in our example - line #26).
But why does jQuery.prototype (line #14 middle) also have these functions (it sets them to it's prototype...)? It's like we're going to do $.addClass() which is invalid.