With the development of the time, there are more and more excellent frameworks in the JavaScript camp, which greatly simplifies our development work, should we think about how they are built when we use these frameworks drink from? If you're not satisfied with just using some out-of-the-box APIs, but getting an insight into their internal implementation mechanisms (API is the fastest thing to depreciate in someone's opinion), the best thing to do is to read their source code, if you can read it.
The last two days to study the source of JQuery , here will I some superficial understanding to share out, improper place please correct me. OK, so let's take a look at how jquery works, and I assume you already have some basic javascript knowledge, and if the basics aren't enough I recommend you to read the two books, JavaScript advanced programming and the understanding of JavaScript. This article is not suitable for JS inside the class, object, function, prototype and other concepts do not know friends.
Let's start with the first word:
First we construct an object to the user, assuming that our framework is called Shaka (my name;).
var Shaka = function () {}; Here we create an empty function with nothing in it, and this function is actually our constructor. In order for our generated objects to invoke the methods defined in prototype, we need to add some methods to the Shaka in a prototype way (Shaka as a class), and then define:
Shaka.fn = Shaka.prototype = {};
The Shaka.fn here are equivalent to shaka.prototype aliases that are convenient for later use and point to the same reference.
OK, we add a SayHello method to add a parameter to the Shaka, so that the basic look of this frame has already been, if it has life then it is now 1 years old, look at the code:
Run Code Box
<script type= "Text/javascript" > var Shaka = function (age) {this.age = age;}; Shaka.fn = Shaka.prototype = {sayhello:function () {alert (' I am ' A little baby, my age was ' + This.age + ' years old. ') }}; var Babyshaka = new Shaka (1); Babyshaka.sayhello (); </script>
[Ctrl + A ALL SELECT hint: You can modify some of the code, and then run]
OK, let's not get excited, we notice that there are some differences between this framework and jquery in use, such as in JQ we can write:
JQuery (' #myid '). SomeMethod ();
How does this work, that is, the jquery () constructor returns an object instance of jquery, so we can call its method on it, so the Shaka constructor should return an instance that looks like this:
var Shaka = function () {return//Returns an instance of Shaka;
So how do we get a shaka example, let's review the prototype method to simulate a class when var someobj = new MyClass (); This time actually creates a new object Someobje, takes the new object as the this pointer, calls the MyClass function, the class constructor, and then Someobj gets the method defined in Myclass.prototype. The this pointer within these methods refers to the current object instance.