Home > Web Front-end > JS Tutorial > The Secret of Creating Instances and Prototypal Inheritance in jQuery_jquery

The Secret of Creating Instances and Prototypal Inheritance in jQuery_jquery

WBOY
Release: 2016-05-16 17:57:58
Original
1007 people have browsed it

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.

Copy code The code is as follows:

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:
Copy the code The code is as follows:

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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template