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.
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?
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?
(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.
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