Why does jQuery do this in its constructor function implementation?

If we look at the latest jQuery source at http://code.jquery.com/jquery-latest.js , we will see the following:

var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); } 

My understanding of the new keyword in Javascript is, in essence, JavaScript passing an empty {} object to the function, and the function superimposes the contents on it through this.blah .

Also from my understanding, new is different from .call / .apply , etc. in that the return object also has a prototype set for the function prototype. Thus, the return value must have a prototype similar to jQuery.prototype.init.prototype (or jQuery.fn.init.prototype ). However, from what I see, its prototype is installed on jQuery.prototype , thus, all the commands available for working with the set.

Why is this? What am I missing in my understanding?

+5
source share
2 answers

If you look deeper into jQuery code , you will see this line:

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

This is for read / structure purposes, so the constructor may have its own method.

There is no real “magic” here, possibly standard JavaScript, although a little less frequently used. This is useful in the case of jQuery, as the library is quite long and it adds good structure / readability.

+1
source

In this source file, find the line “Give init functions to the jQuery prototype for the next instance” :-)

The code sets the prototype jQuery.fn.init link to jQuery.prototype (which is the same as jQuery.fn , I think).

0
source

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


All Articles