Core Architecture Design of jQuery

Source: Internet
Author: User
Talking about jQuery's Core Architecture Design jQuery is no stranger to everyone, so I will not talk about what it is and its role here, the purpose of this article is to discuss jQuery's core architecture design through a simple analysis of the source code, and how jQuery uses the advanced features in javascript to build such a great javascript library.

1 first glance at jQuery

From the perspective of core functions, jQuery only does a simple and ordinary thing: query. Its syntax is so concise and clear that many people will already use jQuery when they don't know what javascript is. A word is used to describe it: the greatest truths are simple. From the design perspective, jQuery provides two types of Methods: static method and instance method. Static methods are directly accessed through $. These methods do not operate on dom elements, but provide some common tools, such as ajax requests and some common operations on strings, in addition, jQuery also provides an extension mechanism for itself. You can use the extend method to compile the components you need. The instance method is different from the static method. It is used to operate on the DOM elements queried by jQuery. When jQuery executes $ (), it constructs a jQuery object, this object stores all the DOM elements queried in the array method, and then implements the DOM operation methods on the prototype chain of this object, such as each () the method is used to traverse every DOM element. You may notice that the object is stored as an array. That is to say, the object built by jQuery is not an array. What is the object? In fact, this object is the core of jQuery, also known as "jQuery object ". Therefore, the focus of this article is to analyze and discuss jQuery objects.

2 jQuery object

In general, jQuery is used as follows:

$('p').each(function(index){     //this ...});

$ ('P') returns a jQuery object after execution. The each () method traverses the DOM elements in this object. Let's first look at $ ('P ') (the source code of this article is taken from jQuery 3.0 ):

jQuery = function( selector, context ) {        return new jQuery.fn.init( selector, context );}

This method is the entry method of $ ('P'). $ is short for jQuery, which is equivalent to jQuery ('P'). It can be seen that this method only does one thing, that is, jQuery is returned. fn. the instance object of the init () function, then jQuery. fn. what is init? Let's look at the following code:

init = jQuery.fn.init = = jQuery.fn;

JQuery. fn. init and init reference the same method. this method queries qualified DOM elements based on selector and returns them. But you will find that this is returned. What is this? We will analyze it later. Let's take a look at the following sentence:

init.prototype = jQuery.fn;

What does this sentence mean? This sentence directs the prototype object of the init method to the jQuery. fn object. What is jQuery. fn? Let's continue to look at the Code:

jQuery.fn = jQuery.prototype = {    // The current version of jQuery being used    jquery: version,    constructor: jQuery,    // The default length of a jQuery object is 0    length: 0,    // Execute a callback for every element in the matched set.    each: function( callback ) {        return jQuery.each( this, callback );    },           splice: arr.splice};

In order to save space, I omitted some of the Code. From here, we can see that jQuery. fn is actually the prototype object of jQuery. this prototype object defines some methods to operate this object. At this point, do you feel a little confused? Don't worry. Let's take a look: jQuery first defines an init method, and then defines a series of operation methods on the prototype of init. Finally, return the Instance Object of the init method. Therefore, the above process can be simplified as follows (represented by pseudocode ):

var init = function(selector,context,root){   //...   return this;}init.prototype = {   length:0,   each:function(callback){      //...   },   splice:[].splice}jQuery = function(selector,context,root){   return new init(selector,context,root);}

So the question is, why is the method in jQuery. fn not directly defined on the prototype of init, but on the jQuery prototype object?

In fact, the purpose of this operation is to improve the query efficiency of jQuery. If it is directly defined on the prototype object of init, each query is executed, this large prototype object will be created in the memory. If this object is defined on the prototype of jQuery, when jQuery is loaded, this object will be initialized and stored in the memory all the time. When you execute $ (), you only need to point the prototype in init to this object, instead of creating the same object each time.

Let's take a look at what this is returned in the init function. As I mentioned in my previous blog, this in the function always points to the callers in the runtime. Who is the caller of init? The caller does not seem to be found in the Code above. In this case, we need to have a deep understanding of the running mechanism of the new operator. I used the new operator description in my previous blog () the execution process is as follows:

new init(selector,context,root) = {    var obj = {};    obj.__proto__ = init.prototype;    init.call(obj,selector,context,root);    return typeof result === 'obj'? result : obj;}

From the above decomposition process, we can see that when javascript creates an instance object through new, it will first create a common object obj, then, point the internal attribute _ proto _ of obj to the init prototype object. Therefore, the prototype chain of obj is changed, and the call method is used in step 1 to call init (), so this in init refers to the obj object here.

After init () is executed, all the matched DOM objects are stored in this object as arrays and returned, that is, the obj object is returned, the new operator will eventually return this obj object as a new instance object. Therefore, the instance object returned by the new operator has two features: First, it contains the DOM query result set, second, its prototype chain inherits the prototype of init, and the prototype of init points to jQuery. fn object, so the instance object also has these operation methods.

Each time jQuery executes a query, it creates a jQuery object. In the same application, all jQuery objects share the same jQuery prototype object. Therefore, the jQuery object not only contains the DOM query result set, but also inherits the operation methods on the jQuery prototype object. In this way, you can directly call methods to operate these DOM elements after the query. This is the core architecture design of jQuery, which is simple, convenient, and practical!

If you still don't understand the above explanation, don't worry. I wrote a complete small project jDate Based on jQuery's design philosophy. You can compare and understand it! The jDate project has been uploaded to GitHub. You can click here to view the complete code: jDate. If you have different opinions, please discuss it!

3 jQuery Defects

Through the analysis of jQuery's core architecture, we will find that every time a query is executed, jQuery will build a complex jQuery object in the memory, although each jQuery object shares the same jQuery prototype, the Query Process of jQuery is far more complex than you think. It must consider different matching identifiers, at the same time, the compatibility of different browsers should be considered. Therefore, if you only perform some simple operations on the DOM, we recommend that you use the native method querySelector instead of jQuery. However, when using the native method, you may have to make some compatibility work for different application scenarios. You must learn to choose between them and do not rely too much on jQuery!

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.