Jquery source code - jquery.fn.init

I am learning how jQuery source code works, I understand that a jQuery object just redirects a call to jQuery.fn.init , where jQuery.fn is just a reference to jQuery.prototype .

Then in the source code there is a line like this:

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

There is a comment to explain what the code does, but I still can't figure it out.

  • Can someone explain what this line of code means? which is described later, and why do we need to install the init prototype in jQuery prototpe?

  • Is there a reason (e.g. avoiding conflicts or readability, or something else) that jQuery source code uses jQuery.fn instead of using jQuery.prototype directly?

+4
source share
1 answer

(This answer is written if you have some understanding of prototype inheritance. If you do not, you need to read an article about it to fully understand what is happening. Try a Google search for “prototype javascript inheritance”.)

When a new jQuery object is created internally, it is created using new jQuery.fn.init() . init is a constructor, so setting the prototype property in this constructor allows newly created jQuery objects to inherit all the properties of this prototype (all jQuery.fn methods).

If only new jQuery() was used, as you seem to assume that the object inherits from jQuery.prototype , but the jQuery function will be executed, which, as you know, is a lot. Instead, the init constructor is used because it does not come with the jQuery function baggage. Setting jQuery.prototype to the same as jQuery.fn.init.prototype allows you to make jqueryobject instanceof jQuery , which is nice, so the reason the jQuery object has a prototype.

+2
source

Source: https://habr.com/ru/post/1446763/


All Articles