Some time ago, when reading JavaScript-based object-oriented programming data, a little bit of question was raised about jquery, which was always in use.
In JavaScript programming, there are two ways to generate objects,
First, the object literal way:
var foo = {
Name: "The Red Leaf",
Age:18
};
The second is to create objects from the constructor:
function Foo () {
this.name = "Red leaf";
This.age = 18;
}
var foo = new Foo ();
In the above formula, Foo is the object constructed by the constructor foo (in JavaScript, the function can be used as a constructor.) So there is an unwritten convention, usually capitalized as the first letter of the function to be used as a constructor.
Back in jquery, the most commonly used object generation in jquery is $ ("#id"), which is obviously not the same as the above two, so let's look at the code to see what kind of encapsulation and transformation jquery has done (the following code is taken from jQuery1.9.1);
Window.jquery = window.$ = JQuery;
JQuery = function (selector, context) {
return new JQuery.fn.init (selector, context, rootjquery);
},
With the above lines we can see that jquery and $ are two equivalent global variables, and $ ("#id") is called the function defined above, equivalent to JQuery ("#id"), the return value of this function is new JQuery.fn.init (selector, context, rootjquery);
That is, $ ("#id") actually calls the Init () constructor to construct an object and return it.
Let's take a closer look at JQuery.fn.init (); What is this jquery.fn, and what is special about the Init constructor? Let's take a look at the code again.
Jquery.fn = Jquery.prototype = {
Init:function (selector, context, rootjquery) {
......
},
....
};
JQuery.fn.init.prototype = Jquery.fn;
by Jquery.fn = Jquery.prototype, FN is a reference to the JQuery prototype object, in fact FN has no other special meaning, in order to prevent confusion to our thinking, we can replace all fn in the above code with the prototype of jquery ( Replace all Jquery.fn with Jquery.prototype).
As to what is special about the Init constructor, we see in jquery that the prototype of Init points to Jquery.fn, which points to the prototype of jquery, Jquery.prototype. The advantage of this is that objects constructed by the Init () constructor can access the methods and properties on the jquery prototype through the prototype chain.
For these variables of the relationship, if there is doubt, you can refer to the following two pictures to help understand, the first one is my own painting, the second Baidu borrowed netizens, said all is a meaning, but the way the painting is different.
On the object composition of jquery 1