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().initis a constructor, so setting theprototypeproperty on this constructor allows newly created jQuery objects to inherit all the properties of this prototype (all the methods ofjQuery.fn).If just
new jQuery()was used, as you seem to suggest, the object would inherit fromjQuery.prototypebut thejQueryfunction would be executed, which as you know does a lot. Theinitconstructor is used instead because it doesn’t come with the baggage of thejQueryfunction. SettingjQuery.prototypeto the same asjQuery.fn.init.prototypejust allows you to dojqueryobject instanceof jQuery, which is nice, so that’s the reason thejQueryobject has a prototype.