0

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;
11
  • new jQuery.fn.init(...) is a call to jQuery.fn.init, not jQuery. Commented Feb 17, 2019 at 1:49
  • Also, jQuery.fn is an alias of jQuery.prototype so don't let that confuse you Commented Feb 17, 2019 at 1:53
  • 1
    It is possible to review each part of jQuery without reading all 10,000 lines, for example, "core" github.com/jquery/jquery/blob/master/src/core.js Commented Feb 17, 2019 at 2:13
  • @andrew - yes, I put that info into my question. However, I still do not understand how to answer my question. Commented Feb 17, 2019 at 2:40
  • 1
    That's the way JavaScript works. new a.b.c is not (new a).b.c, it's new (a.b.c). Commented Feb 17, 2019 at 3:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.