JavaScript imitates jquery to make the framework prototype

Source: Internet
Author: User

jquery is so powerful that I decided to imitate jquery to build a wheel and learn how jquery is using various techniques to achieve those very powerful functions, while making wheels. Since I was imitating jQuery, I decided to name the new framework jqc,jquery copy. So let's start from zero to the prototype of a framework, if there is a fallacy to tell.

Sandbox mode

At the beginning of everything, we need to define a sandbox to put all our code inside, leaving only part of the interface for external invocation. All variables within the sandbox are local variables and do not pollute the global variable environment.

(function (window,undefined) {var jqc = function () {//...} .... window.jqc = JQC;}) (window)

  

In the self-calling function There are two parameters window and undefined, and pass in a window as an argument. When you use the Window object internally, you can query the window object directly inside the function without needing to look up one layer at a time in the scope chain. Instead of passing in the second argument, the value is undefined when using the undefined variable inside a function. This is to prevent the low version of the browser does not have undefined keyword, when using undefined because there is no undefined variable to cause the browser error.
In the end, the JQC is hung on the Window object, providing an interface to operate on, while the other variables are hidden and protected.

constructor function

After that, we need a constructor to return the object. In jquery, the new jquery () is equivalent to jquery. is because the attributes of the constructor invocation pattern are used, and when the function declared with the New keyword returns an object, the return object is returned.

(function (window,undefined) {var f = function () {};var JQC = function () {return new F ();} WINDOW.JQC = JQC;}) (window)

  

In other words, new JQC () and JQC () are equivalent in the above code. At this point, the effect of jquery is roughly the same, but one thing to note is that the exposed interface is only JQC, and the most important constructor F is not public, the outside world can not modify F, can not write plug-ins for JQC.
In jquery, the constructor is linked to the jquery function, and the constructor can be extended simply by exposing jquery-that is, writing the plugin for jquery.

var jQuery = function (selector, context) {return new JQuery.fn.init (selector, context, rootjquery);} Jquery.fn = Jquery.prototype = {init:function () {//...}} JQuery.fn.init.prototype = Jquery.fn;

  


As you can see, in jquery, calling the jquery function will instantiate an Init constructor return, where Init is equivalent to the F-constructor I wrote above. jquery puts the Init constructor in the prototype of the jquery function and assigns the prototype object of jquery to the Init prototype object, so that modifying the prototype object of jquery is equivalent to modifying the prototype object of the constructor init. So it is possible to extend the prototype of jquery with only one interface, that is, to implement a plugin for jquery.
Moreover, the source also provides a shorthand FN for the prototype object of the jquery function, so that when accessing the prototype object, you do not need to write "protoype" such a long word, just use "FN".

(function (window,undefined) {var jqc = function () {return new Jqc.fn.init ();} Jqc.fn = Jqc.prototrype = {constructor:jqc,init:function () {},//instance can inherit the method here Add Appendto:function () {},push:function () { },each:function () {}}//adds a method to JQC can be directly jqc.xxx = function () {}jqc.push = function () {};jqc.each = function () {}; Jqc.islikearr = function () {};jqc.isstring = function () {};jqc.isfunc = function () {};jqc.isdom = function () {}; Jqc.fn.init.prototype = JQC.FN;WINDOW.JQC = JQC;}) (window)

  

Modify the code as above, the skeleton of the JQC frame is roughly molded. The next step is to keep adding methods. But there is something missing, look at the note, if you continue to add methods in the prototype object will be very bloated, various functions of the methods stacked together. The same is true for adding methods to JQC, which repeatedly writes jqc.xxx = function () {}. So we need a way to group all the methods.

Extensions and sub-modules

Let's see how jquery solves the problem.

Jquery.extend = JQuery.fn.extend = function () {//method to implement inheritance}

  

A method named Extend is implemented in jquery for the jquery function and for the prototype object of jquery, which is the function of assigning all properties of an incoming object to this. Since the extend algorithm is particularly large, let's implement a simple extend method.

Jqc.extend = Jqc.fn.extend = function (obj) {var k;for (k in obj) {this[k] = obj[k];}}

This allows us to add a new property to JQC by calling Jqc.extend. Add a method to the Jqc prototype object by Jqc.fn.extend. Now that the JQC framework is rudimentary, let's reorganize the method above. Since most of the algorithms in jquery are complex, I'm not going to copy the various methods of jquery and sacrifice some compatibility to implement a broadly available framework in a simple way.

(function (window,undefined) {var jqc = function () {return new Jqc.fn.init ();} Jqc.fn = Jqc.prototrype = {constructor:jqc,length:0,//initialization method Init:function (selector, context) {var context = Context | | d ocument;//determines if the incoming is null ' undefined 0if (!selector) return;//determine if selector is a string if (jqc.isstring (selector)) {if (selecto R.charat (0) = = = "<") {//When an HTML tag is called the Parsehtml method gets the DOM array//Gets the array call Pusharr method added to itself This.push (parsehtml (selector));} else{//Otherwise calls the Select method to get the DOM array//Gets the array call Pusharr method added to itself This.push (select (Selector,context));} Determines whether selector is a DOM node} else if (Jqc.isdom (selector)) {//Adds DOM elements to itself This.push ([selector]) when a DOM element is passed in;//Determines whether the incoming DOM array } else if (Jqc.islikearr (selector) && jqc.isdom (selector[9])) {This.push (selector);//Determine if the incoming is a JQC object} else if ( JQC.ISJQC (selector)) {return this;}},push:function () {}}jqc.fn.init.prototype = jqc.fn;//Tool class method module Jqc.extend ({// Implement the Push method push:[].push,//Loop Traversal Method Each:function () {}});//Determine the type module jqc.extend ({//Determine whether an array or a pseudo-array islikearr:function (obj) {}), Isstring:function (obj) {},isfunc:function (obj) {},//Whether the DOM object Isdom:function (obj) {},//is Jqc object Isjqc:function (obj) {}});// Dom Action Method Jqc.fn.extend ({appendto:function (selector) {}})//html convert DOM object and return array object var parsehtml = function (HTML) {}// Querying the DOM element and returning the array object var select = function (selector) {};WINDOW.JQC = JQC;}) (window)

  

The above code removes the method body of all methods, preserving only the method body of the Init constructor. With the pseudo code above, you can see that the JQC framework has been roughly shaped, and that future extensions can use extend to add new methods to JQC or JQC prototype objects, and also to group methods by function by different extend code blocks, and outside the sandbox, You can also add new methods to the JQC framework to write the JQC plug-in by extend.
The JQC framework simulates how the jquery framework is used, and if it complements the above code, it can be JQC ("<div>1</div>"). AppendTo ("Body") to create a DIV element and add it to the body.

JavaScript imitates jquery to make the framework prototype

Related Article

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.