Let's continue with the previous jQuery source code analysis (1) and continue to look at the code below.
JQuery's framework design is very clever. Maybe 1.0 and 1.6.x have great changes in code, but the basic principle is the same. They all use javascript prototype for inheritance, let's look at the following code:
Function jQuery (a, c ){
// Code Segment 1: Several code lines are omitted here
// If the context is global, return a new object
If (window = this)
Return new jQuery (a, c );
// Code Segment 2: Several code lines are omitted here
}
Here, we omit some unimportant code. jQuery is the entry function.
As you know, javascript Functions are functions and classes. When you create a new function, this function becomes a class constructor. this in the function points to the new instance.
While normally calling a global function, this is pointing to the window variable.
So the above Code is easy to understand.
When the jQuery function is called for the first time, jQuery acts as an object factory. when it encounters if (window = this), it immediately creates a new jQuery object, calls jQuery again, and returns the object.
When calling the jQuery function for the second time, jQuery acts as the constructor. this points to the new instance.
The code itself is okay, but the design is a bit poor. In the position of code segment 1, The jQuery function is called twice, and this is directed to the window and jQuery instance objects respectively, this is a bit bad. Therefore, this is not used in code segment 1, but in code segment 2.
In line with the single responsibility principle, a function should only do one thing. So later versions of jQuery put the code of the new object into a new function init.
Author: baozhifei