With the development of the times, more and more excellent frameworks have appeared in the JavaScript camp, which greatly simplifies our development work. When we use these frameworks, should we also think about their origins and think about how they are built? If you are not satisfied with just using some ready-made APIs, but have a deep understanding of their internal implementation mechanisms (according to someone, APIs are the fastest depreciating things), the best way is to read their source code. The premise is that you can read it.
I have studied the source code of jQuery in the past two days, and here I will share some of my superficial knowledge. Please correct me if I am inappropriate. Okay, let's take a look at how jQuery works. I assume that you already have some basic knowledge of JavaScript. 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 understand concepts such as classes, objects, functions, prototypes, etc. in js.
Let’s start from the very beginning:
First construct an object to the user, assuming our framework is called Shaka (my name ;) )
var Shaka = function(){}; Here we create an empty function with nothing in it. This function is actually our constructor. In order for the object we generate to call the methods defined in the prototype, we need to add some methods to Shaka using the prototype (think of Shaka as a class), so we define:
Shaka.fn = Shaka.prototype = {};
Shaka.fn here is equivalent to the alias of Shaka.prototype for future use. They point to the same reference.
OK, let's add a sayHello method and add a parameter to Shaka, so that the most basic appearance of this framework is already there. If it is alive, it is now 1 year old. Look at the code:
Run code box
[Ctrl+A Select All Tips: You can modify part of the code first and then press Run]
Okay, don’t get excited. We noticed that there are some differences in the use of this framework and jQuery. For example, in jq we can write like this:
jQuery('#myid').someMethod();
How is this done, that is to say, the jQuery() constructor returns a jQuery object instance, so we can call its method on it, so Shaka's constructor should return an instance, and it should look like It looks like this:
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, which is the constructor of the class, and then someObj obtains the methods defined in MyClass.prototype. The this pointer in these methods refers to the current object instance.