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.
Why does line #15 (
constructor: jQuery,
) exist? all it does (imho) is to tell the prototype object that it's ctor function is jQuery.
Yes. People do expect to find new jQuery().constructor == jQuery
.
how does jQuery use that fact ?
For example, the pushStack
internal method uses this.constructor()
to create new instances - which also allows inheritance from jQuery.
But why does jQuery.prototype (line #14 middle) also have these [jQuery.fn] functions (it sets them to it's prototype...)?
To cite this answer:
One of the reasons behind this is certainly that they want to accomodate people that might modify
jQuery.prototype
instead ofjQuery.fn
.However another valid reason is that they perhaps wanted
somejQueryObj instanceof jQuery
to returns true, while it normally wouldn't.
It's like we're going to do
$.addClass()
which is invalid.
No, how so? Are you confusing the standard .prototype
property of every (constructor) function with the internal prototype chain?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With