Write the jquery framework from scratch

Source: Internet
Author: User

Abstract: This article describes the JS framework development steps based on jquery from simple to complex. We hope that you will have a general understanding of the frameworks such as jquery.

With the development of the times, more and more excellent frameworks have emerged in the Javascript camp, greatly simplifying our development work, when we use these frameworks, should we also think about how they are built? If you are not satisfied with using some existing APIs, but with an in-depth understanding of their internal implementation mechanisms (according to someone, the API is the fastest thing to deploy), the best way is to read them.Source codeThe premise is that you can understand it.

I have studied jquery's source code in the last two days. Here I will share some of my rough ideas. please correct me for any mistakes. Now let's take a look at how jquery works. I suppose you already have some basic JavaScript knowledge. If the basics are not enough, I recommend you read JavaScript advancedProgramDesign and understanding JavaScript. This article is not suitable for users who do not know about classes, objects, functions, prototype, and other concepts in JavaScript.

Let's start:
First, construct an object for the user. Assume that our framework is called Shaka (my name ;))
VaR Shaka = function () {}; here we have created an empty function with nothing in it. This function is actually our constructor. To enable the generated object to call the methods defined in prototype, we need to add some methods to Shaka by using the prototype method (using Shaka as a class), so the definition is as follows:
Shaka. fn = Shaka. Prototype = {}; here, Shaka. FN 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. In this way, the framework is basically ready. If it is alive, it is 1 year old.Code:

<! Doctype HTML public "-// W3C // dtd html 4.01 strict // en" "http://www.w3.org/TR/html4/strict.dtd"> <br/> <HTML> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> </pead> <br/> <body> <br/> </ptml> <br/>

[Ctrl + A select all tips: you can modify some code and then press run]

Well, don't be excited. We noticed that this framework is different from jquery in terms of usage. For example, in JQ, we can write it 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 above, therefore, the Shaka constructor should return an instance, which looks like this:
VaR Shaka = function () {return // return Shaka instance;}; so how do we obtain a shaka instance, let's first review the VaR someobj = new myclass () when we use prototype to simulate classes. In this case, we actually create a new object someobje, use the new object as the this pointer, and call the myclass function, that is, the class constructor, and then someobj obtains. methods defined in prototype. The this pointer in these methods indicates the current object instance.

A factory method is used in jquery to create an instance. This method is located in jquery. in prototype, now let's redefine Shaka. prototype, add an init method to it to return a shaka instance, and slightly change the Shaka constructor:

VaR Shaka = function (AGE) {return New Shaka. FN. INIT (AGE );};

Shaka. fn = Shaka. Prototype = {
Init: function (AGE) {This. Age = age; return this ;},
Sayhello: function () {alert ('I am a little baby, my age is' + this. Age + 'ears old .');}
};

Shaka. FN. init. prototype = Shaka. FN; // new Shaka. FN. the object created by Init (AGE) has the prototype of the init method pointing to the object method. Therefore, we direct the prototype of the init Method to the prototype of Shaka, so that the created object has Shaka. methods defined in prototype.

Okay, now our baby is a bigger baby. Say hello first:

<! Doctype HTML public "-// W3C // dtd html 4.01 strict // en" "http://www.w3.org/TR/html4/strict.dtd"> <br/> <HTML> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> </pead> <br/> <body> <br/> </ptml> <br/>

[Ctrl + A select all tips: you can modify some code and then press run]

Well, it seems a bit like this, but this is not enough. To be practical, we will implement some functions of the Val () method in jquery in the new framework, this method returns the input value of the specified ID when the parameter is not added, and sets the input value when the parameter is added, which is the same as jqery, we agree to use the "#" symbol when using ID to search for objects. Pass the target ID to be searched as the constructor parameter, and we will send it to Shaka. add a Val () method to prototype and add a selector attribute to Shaka to store the target to be searched.:
Shaka. fn = Shaka. prototype = {
init: function (selector) {This. selector = selector; return this ;},
VAL: function (newvalue) {// method implementation code }< BR >};
var Shaka = function (selector) {return New Shaka. FN. init (selector) ;};

<! Doctype HTML public "-// W3C // dtd html 4.01 strict // en" "http://www.w3.org/TR/html4/strict.dtd"> <br/> <HTML> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> </pead> <br/> <body> <br/> <form method =" Post "Action =" "name =" myform "> <br/> How old are I? <Br/> <input id = "myinput" type = "text" value = "Hello world! "Size =" 50 "/> <br/> </form> <br/> </body> <br/> </ptml> <br/>

[Ctrl + A select all tips: you can modify some code and then press run]

Take a break, By the way insert an advertisement: my blog http://darkangle.cnblogs.com

So far, we have created a prototype of framework that can work. In order to make the program more convenient to call, for example, jquery can use the $ symbol for short, we also get one, before that, let's review two things:

1. variables can be defined in the script as follows:
VaR Foo = 'something ';
Bar = 'otherth ';
These two statements are valid, but have different meanings. The first statement creates a new variable, and the second statement defines an attribute of the window object, which is equivalent to window. bar = 'otherthing '; so we want to make our Shaka have the following calling method capabilities: $. somemethod (); you need to set Shaka as an attribute of window, so our Shaka constructor must be written as follows:
VaR Shaka = Window. Shaka = Window. $ = function (selector) {return New Shaka. FN. INIT (selector );};

2. Javascript anonymous functions.
Basic Form of creating and executing an anonymous function: (function () {alert ('Hello world! ') ;}) (); Why do we need anonymous functions? Because we don't want to expose the internal implementation of Shaka, it is easy to conflict with other code and only provides a single entry, we can test it like this:

<! Doctype HTML public "-// W3C // dtd html 4.01 strict // en" "http://www.w3.org/TR/html4/strict.dtd"> <br/> <HTML> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> </pead> <br/> <body> <br/> </ptml> <br/>

[Ctrl + A select all tips: you can modify some code and then press run]

Then there is another problem that needs to be solved. Our frameworks have been made, but they are still very simple. Before that, we need to make them work together with other frameworks, which brings about a problem, if we use $ as a short form, it will conflict. Like jquery, we need to provide a noconfilit method to "authorize" $. Add the following code at the beginning of our program:
VaR _ $ = Window. $;
It means to put the previously defined $ object reference in _ $, and then we will extend a method to Shaka, this method can also be used if other developers need to expand on their own (the extend method of jquery provides more powerful functions, Please study it on your own ):
(Function ($) {// extend method definition.}) (Shaka );
This method is called by using Shaka as the parameter of this anonymous function.
As we have mentioned earlier, Shaka. FN is the alias of Shaka. Prototype. Therefore, we need to add a new method in Shaka. prototype to write it like this.
(Function ($ ){
$. FN. noconflict = function (){
Window. $ =_$; // return $ to the reference obtained at the beginning.
};
}) (Shaka );

Now let's look at a complete:

<! Doctype HTML public "-// W3C // dtd html 4.01 strict // en" "http://www.w3.org/TR/html4/strict.dtd"> <br/> <HTML> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> </pead> <br/> <body> <br/> <form method =" Post "Action =" "name =" myform "> <br/> <p> How old are I? </H1> <br/> <input id = "myinput" type = "text" value = "Hello world! "Size =" 50 "/> <br/> <input id =" otherinput "type =" text "size =" 50 "/> <br/> </form> <br/> </body> <br/> </ptml> <br/>

[Ctrl + A select all tips: you can modify some code and then press run]

it seems good now. Our Shaka baby is 5 years old.) Of course, this is just a simple thing, A lot of effort is required to achieve robust and powerful functions. I hope that you will train your children to become adults. Good luck!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.