Such as new Object(), new Date(), etc.! (object has {}, and array has shortcuts such as []. We mainly discuss the new method.)
We have never used new when using jQuery. Does it use other methods to generate instances? Woolen cloth? Are you not using the prototype attribute? In fact, he has used them all, but the internal processing is very clever, which improves the ease of use. Let's take a look at his source code.
funtion jQuery(selector, context){
return new jQuery.fn.init( selector, context );
}
Here you can see that jQuery has a constructor, and new is used to create instances. So what is jQuery.fn? There is such a process at the back:
jQuery.fn = jQuery .prototype={
init: function (){}
}
So we understand that jQuery’s constructor is the init method on its prototype, not function jQuery. In this case, every time $() is called, it will create an instance using init on the jQuery prototype, and then a new problem arises. If you use init to create an instance, this object inherits the methods on init's prototype but not the methods on jQuery prototype. So how does it implement prototype inheritance?
jQuery.fn.init.prototype = jQuery.fn;
Here he has such a process, assigning jQuery.fn to jQuery.fn.init.prototype. This step is very critical. Let's see what these are.
jQuery.fn is jQuery.prototype
jQuery.fn.init.prototype is jQuery.prototype.init.prototype
This processing is equivalent to
jQuery.prototype = jQuery.prototype.init.prototype
Then whenever we call $(), jQuery will use the new operator to call init on his prototype to create an instance. This instance created by init will Inherits all methods on jQuery prototype, and the __proto__ internal property of this instance will point to jQuery's prototype property.
In addition, we noticed this processing:
jQuery.fn = jQuery.prototype
This is to avoid frequent operations on jQuery.prototype, so jQuery.fn is cached jQuery.prototype.
The processing of these is really very clever. Instance creation is handled internally without the need for users to use new to generate instances. It also handles the prototype very beautifully to ensure that multiple instances are shared to reduce resource expenditure.