Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding jquery source code - jquery.fn.init

I am looking into how jQuery source code works, I understand the jQuery object just forwards a call to jQuery.fn.init where jQuery.fn is just a reference to jQuery.prototype.

Then in the source code, there is this line:

// 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 understand it.

  1. Can someone explain what does this line of code means? what later instantiation is it talking about and why do we need to set init's prototype to jquery's prototpe?

  2. is there a reason (like avoiding conflicts or readability or whatever) that jQuery source code is using jQuery.fn instead of using jQuery.prototype directly?

like image 726
kabaros Avatar asked Nov 04 '22 11:11

kabaros


1 Answers

(This response is written assuming you have some understanding of prototypal inheritance. If you don't, you need to read an article about it to fully understand what's going on. Try doing a Google search for "prototypal inheritance javascript".)

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

If just new jQuery() was used, as you seem to suggest, the object would inherit from jQuery.prototype but the jQuery function would be executed, which as you know does a lot. The init constructor is used instead because it doesn't come with the baggage of the jQuery function. Setting jQuery.prototype to the same as jQuery.fn.init.prototype just allows you to do jqueryobject instanceof jQuery, which is nice, so that's the reason the jQuery object has a prototype.

like image 134
Nathan Wall Avatar answered Nov 12 '22 18:11

Nathan Wall