In my previous article, I elaborated on the general framework of jquery, knowing that all the code was written in a self-invoking anonymous function, and passed in the Window object, the source code is this:
(function(window, undefined) {...}) (window);
We know by alert (jquery) that it is an object, so how is this object constructed? We use $ (document) to get an element in a similar way, just like calling a normal method, is jquery a normal function? What if the constructor is not a common form of new $ (document)?
In fact, jquery is an object-oriented JS library, there are constructors, each time the jquery method is called to instantiate a Jqeury object, but jquery is very clever.
First of all talk about JS object-oriented: JS is not object-oriented language, but a lot of object-oriented writing, it is recommended to see a spirit of "JavaScript advanced Programming" in the object-oriented programming section. The more commonly used notation in many methods is the construction plus prototype, the following example:
varperson=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+ ' say ' +msg); }};varTom=NewPerson (' Tom ', 23); Tom.init (' Hello ');//Tom says hello.
In fact, jquery is also used in this way only with a smarter approach, and then see how the jquery constructor is different
// Define A local copy of JQuery var function (Selector, context) {// The JQuery object is actually just the Init constructor ' enhanced '
return
New
jQuery.fn.init (selector, context, rootjquery);},
From the source you can see that the real function in jquery is the Init method, and when we call jquery we return the result of new Init () instead of the direct new jquery ().
What is Jquery.fn, in the back we will see a code like this
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