such as New Object (), New Date (), and so on! (Object has {}, the array has [] such a shortcut, we mainly discuss new this way.) )
When we used jquery, we never used new, did he use other methods to generate the instance? Are you not using the prototype attribute? In fact, he has used, but the internal processing is very clever, improve the use of the alacrity. Let's take a look at his source code.
Copy Code code as follows:
Funtion JQuery (Selector, context) {
Return to New JQuery.fn.init (selector, context);
}
Here you can see that jquery has a constructor, and it also creates an instance with new. So what is Jquery.fn? There is a process that follows:
Copy Code code as follows:
Jquery.fn = jquery.prototype={
Init:function () {}
}
So we understand that jquery's constructor is the Init method on his prototype, not the function jquery. So every time you call $ () he creates an instance with Init on the jquery prototype, so the new problem comes. If you create an instance with Init, and the object inherits the method on the prototype of Init and does not inherit the method on the jquery prototype, how does he implement the prototype inheritance?
JQuery.fn.init.prototype = Jquery.fn;
Here he has one such process, assigning Jquery.fn to JQuery.fn.init.prototype, a step that is critical. Let's see what these are.
Jquery.fn is Jquery.prototype.
JQuery.fn.init.prototype is JQuery.prototype.init.prototype.
This process is equivalent to
Jquery.prototype = JQuery.prototype.init.prototype
So whenever we call $ (), jquery uses the new operator to invoke the Init on his prototype to create an instance where the instance created by Init inherits all the methods on the jquery Protype, and the instance's __proto__ The internal properties point to the prototype attribute of jquery.
In addition, we note this process:
Jquery.fn = Jquery.prototype
This is his to avoid frequent operation Jquery.prototype, so cache jquery.prototype with Jquery.fn.
The handling of these is very ingenious, the internal processing of instance creation without the user using new to generate instances, and very beautiful processing prototype to ensure that multiple instance sharing method to reduce resource expenditure.