With the development of the times, more and more excellent frameworks have appeared in the JavaScript camp, which has greatly simplified our development work. When we use these frameworks, should we also think about how they are built? If you are not satisfied with just using some ready-made APIs, but rather have a deep understanding of their internal implementation mechanisms (as someone says, APIs are the fastest depreciation thing), the best way is to read their source code. The premise is that you can understand it.
I have studied the source code of jQuery in the past two days. Here I will share some of my superficial understandings. Please correct me if there are any inappropriate points. Okay, let's take a look at how jQuery works. I assume you already have some basic javascript knowledge. If the basics are not enough, I recommend you to read the two books "JavaScript Advanced Programming" and "Understanding JavaScript". Book. This article is not suitable for friends who do not have a understanding of concepts such as classes, objects, functions, prototypes, etc. in js.
Let's start with the beginning:
First, construct an object for the user, assuming that our framework is called Shaka (my name;) )
var Shaka = function(){}; Here we create an empty function with nothing inside, this function is actually our constructor. In order for the generated object to call the methods defined in the prototype, we need to add some methods to Shaka in the prototype (taking Shaka as a class), so we define:
Shaka.fn = Shaka.prototype = {};
Here, Shaka.fn is equivalent to the alias of Shaka.prototype, which is convenient for future use. They point to the same reference.
OK, let's add a method to sayHello and add a parameter to Shaka, so that the most basic framework is already there. If it has life, then it is 1 year old now. See the code:
Run the code box
[Ctrl+A All selection tips: You can modify some code first, and then press Run]
OK, don't be excited, we noticed that there are some differences between this framework and jQuery in use, for example, in jq we can write this way:
jQuery('#myid').someMethod();
How does this work? That is to say, the constructor jQuery() returns an instance of jQuery, so we can call its method above, so Shaka's constructor should return an instance, which looks like it should be This looks like:
var Shaka = function(){ return //Return the instance of Shaka; };
So how do we get an instance of Shaka? Let's first review when using prototype to simulate a class var someObj = new MyClass(); At this time, we actually create a new object someObje and use the new object as this pointer. Call the MyClass function, that is, the class constructor, and then someObj obtains the methods defined in MyClass.prototype. This pointer in these methods refers to the current object instance.