jquery is an object-oriented approach with constructors, and each time the jquery method is invoked, an Jqeury object is instantiated, but jquery is a very clever way to learn.
JS is not an object-oriented language, but a lot of object-oriented writing, it is recommended that you look at a spirit of "JavaScript advanced Programming" in the object-oriented programming section. In many ways, the most common way to do this is to construct a prototype, the following example:
var person=function (name,age) {this.name=name; This.age=age;} person.prototype={Constructor:person, Init:function (msg) {This.say (msg); }, Say:function (msg) {alert (this.name+ ' says ' +msg '); }};var tom=new person (' Tom ', 23); Tom.init (' hello ');//Tom says hello.
Then let's take a look at the jquery constructor.
Define a local copy of Jqueryvar jQuery = function (selector, context) {//The JQuery object is actually just the Init Constructor ' enhanced ' return new JQuery.fn.init (selector, context, rootjquery);},
You can see that the real function in jquery is the Init method, and when we call jquery it will be new Init () instead of new jquery ().
Jquery.fn is what, in the back we will see such a code Jquery.fn = Jquery.prototype = {...
This is a good understanding, in fact Jquery.fn is the prototype object that is, in the jquery prototype there is an Init method, this method is the real constructor. The advantage of this writing is that you do not need to write $ (). Init () is initialized directly, but there is one more problem is that since Init is the constructor, then the method instance that we write on jquery is not called. Init's instantiation naturally only calls Init's method, See this code in the future
Give the init function The JQuery prototype for later instantiationjQuery.fn.init.prototype = Jquery.fn;
Before Jquery.fn=jquery.protype, this means that the prototype of jquery is assigned to the prototype of Init, so that the original method of jquery is naturally init, By constructing this way, s makes it very simple to use the JQuery method without the need for a new jquery () operation or the need to manually initialize the line to invoke the normal function as easily.
The analysis of JQuery's constructor function