I'm learning Javascript and trying to understand the jQuery code as an exercise. I'm looking at the un-minified development version of jQuery.js (a recent version). It's around 10,000 lines long and I am just attempting to understand the basic structure and what is done when the jQuery object is created upon every invocation of $(...)
.
There is an answer here that provides a "simple structure that resembles the architecture of jQuery." This is fantastic and it helped me a lot. However, there seems to be a crucial difference between it and the actual code, and this difference relates to the part I don't understand. In the simple example, we have:
var foo = function ...
return new foo ...
There is nothing strange about that. However, in the actual jQuery, we have:
var jQuery = function ...
return new jQuery.fn.init ....
In the definition of jQuery, we need a prototype, but that prototype is (I supposed) only created when new jQuery
has finished execution. We need to add the init method to that prototype as well. But all this is seemingly getting done out of order in the statements above.
The other questions I have found on this topic do not answer my specific question. For example, this one may seem similar, but it doesn't address my question.
So how does this work?
Here are a few of the code fragments I'm looking at:
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
and
jQuery.fn = jQuery.prototype ...
and
init = jQuery.fn.init = function( selector, context ) { ...
and
window.jQuery = window.$ = jQuery;
return jQuery;