Analysis of jQuery's operating mechanism and Design Philosophy

Source: Internet
Author: User

It is short, concise, easy to use, efficient in performance, and can greatly improve the development efficiency. It is one of the best auxiliary tools for developing Web applications. Therefore, most developers discard Prototype and choose jQuery for Web development.

When using jQuery, some developers often encounter many problems because they only know how to use jQuery and do not understand the running principle of jQuery. Most of these problems are caused by improper use, and few of them are jQuery bugs. If we do not understand the running mechanism and core source code, it is difficult to write a high-performance program based on the jQuery class library.

When debugging jQuery-based programs, we spend most of our time tracking the status of jQuery objects for analysis. However, unlike Ext and YUI, jQuery code is a bit obscure, difficult to understand. That is to say, if you want to use jQuery well, you must be clear about its source code.

JQuery Design Philosophy

Before using jQuery, we all ask what jQuery is? JQuery is a class library that provides auxiliary functions for Web JavaScript development like prototype and mootools. So why jQuery? Before jQuery appeared, Prototype and YUI were all mature Js frameworks with different characteristics. Why abandon them and use jQuery, which is an outstanding feature, to attract developers?

To answer this question, we must understand jQuery's design philosophy. Recall or imagine how we use JavaScript in Web development? Most of the time, getElementById is used to find the Dom element in the DOM document, and then the value or set value, innerHTML is used to retrieve or set its content, or event listening (such as click ), in terms of style control, we will change the height, width, and display to achieve visual effect. For Ajax, it is also used to add content to an element of the page.

To sum up, we are operating the DOM elements. This element may be one or more. This element may be a Document, Window, or DOM element. In this way, our task is the second largest part. One is to find the DOM element, and the other is to operate the DOM element.

Be familiar with it, whether using direct search like getElementById or using Element. the indirect search methods such as lastChild are not very difficult. For DOM elements, DOM operations are also very rich and not very difficult to use? So what is the use of the Class Library? The most difficult problem is browser compatibility. All JavaScript frameworks need to solve this problem and simplify the built-in operations of JavaScript.

Prototype can be said to have created a precedent for Js class libraries, giving us a fresh feeling. It solves the compatibility issues of most browsers. At the same time, it simplifies the issue of errors written by regular books with long and difficult to remember original function names (replacing getElementById with $ (xx), provides Ajax access, extends Array, Object, functions, events, and other JavaScript native objects.

But these still cannot meet the development needs. For example, to search for DOM elements in the DOM tree, we can only use the element ID, but we want a more convenient search method, at the same time, we also hope to have a unified entrance. The learning curve is too high or difficult to use.

JQuery is here to unify everything in the jQuery object. JQuery objects are used. In fact, jQuery's pioneering work is like its name: query. Its powerful search function eclipses all frameworks. JQuery is actually a queryer. On the basis of the queryer, you can also perform operations on the searched elements. In this way, jQuery is the unified query and operation. Queries are portals and operations are results.

JQuery can also be divided into two parts in implementation. One part is jQuery's static method, which can also be called a practical method or a tool method. It is directly referenced through the jQuery namespace of jQuery. xxx. The second part is the jQuery instance method. The jQuery instance is generated through jQuery (xx) or $ (xx) and then referenced through this instance. Most of these methods are implemented by using static method proxies. Real functional operations are implemented in jQuery's static method. These functions are subdivided into the following parts:

1. Selector: Find the element. This search not only contains ~ CSS Selector of CSS3 also includes some functions that can be extended for direct or indirect searches.

2. Attribute operations on Dom elements. Dom elements can be viewed as html tags. Operations on attributes are operations on the attributes of tags. This attribute operation includes addition, modification, deletion, and value.

3. Operations on CSS styles of Dom elements. CSS controls the display of pages. Operations on CSS must include common CSS functions such as height, width, and display.

4. Ajax operations. Ajax is used to asynchronously fetch data from the server and perform related operations.

5. Event operations. Unified processing of Event compatibility.

6. animation (Fx) operations. It can be seen as an extension of CSS styles.

JQuery Object Construction

Generating or constructing a jQuery object is actually building and running a selector ). Since it is a query, the results (DOM element) will certainly be searched before these results will be operated. So where are the search results stored? The best part is, of course, the inside of the jQuery object. The search result may be an element or multiple elements, for example, a NodeSet set ). That is to say, there is a set inside the jQuery object. This collection stores the DOM elements found.

But the jQuery object mentioned in the previous section is the unified entry for all operations, so its construction cannot be limited to finding DOM elements from the DOM document, it may also be a Dom element transferred from another collection, or a DOM element generated from an HTML string.

The jQuery document provides four methods: jQuery (expression, [context]), jQuery (html), jQuery (elements), and jQuery (callback) there are four ways to create jQuery objects. JQuery can be replaced by $. These four types are frequently used. In fact, jQuery parameters can be any element and can constitute jQuery objects.

For example:

1. $ ("P") shows that the parameter can be a set of jQuery objects or ArrayLike.

2. $ () is short for $ (document.

3. $ (3) puts 3 in a collection of jQuery objects.

For elements such as $ (3), such as elements in the ArrayLike set, are not DOM elements. We recommend that you do not construct jQuery objects. jQuery object methods are applicable to DOM objects. If you do not know how to use it, it is likely to cause errors. As mentioned above, it is still difficult to understand its principles. Now we will analyze it from the source code perspective:

No object is generated by calling jQuery (xxx), and this of it points to the Window object. So how do jQuery's instance methods inherit from them? Take a look:

Var jQuery = window. jQuery = window. $ = function (selector, context)
{Return new jQuery. fn. init (selector, context );
};
This is the general entry of jQuery. jQuery objects do not actually inherit the methods in their prototype through new jQuery. The jQuery object is actually the object generated by the jQuery. fn. init function. We can see that it is of little significance to add some function set objects for jQuery. prototype. Because we can use new jQuery (), but the generated jQuery object will be discarded at return. Therefore, it is best not to use new jQuery () to construct jQuery objects. The jQuery object is actually new jQuery. fn. init. Therefore, jQuery. fn. init. prototype is the operation method for hanging jQuery objects. For example

JQueryjQuery. fn. init. prototype = jQuery. fn;
There may be time to worry about implementing jQuery in line 589. put the function in fn in jQuery. fn. init. prototype, then use jQuery. fn. what should I do with the extend method? Here is actually a reference to jQuery. fn. When extending jQuery, you only need to extend the relevant function extend to jQuery. fn. Now let's take a look at how jQuery. fn. init completes the work:
Copy codeThe Code is as follows:
Init: function (selector, context ){
Selectorselector = selector | document; // determines whether the selector exists.

// In the first case, Handle $ (DOMElement) indicates a single Dom element, ignoring the context

If (selector. nodeType ){
This [0] = selector;
This. length = 1;
Return this;
}

If (typeof selector = "string") {// selector is string
Var match = quickExpr.exe c (selector );
If (match & (match [1] |! Context )){
If (match [1]) // process the second case $ (html)-> $ (array)
Selector = jQuery. clean ([match [1], context );
Else {// Case 3: HANDLE: $ ("# id") // process $ ("# id ")
Var elem = document. getElementById (match [3]);
If (elem ){
// IE returns the name = id element. If so, document. find (s)
If (elem. id! = Match [3])
Return jQuery (). find (selector );
// Construct a new jQuery (elem)
Return jQuery (elem );
}
Selector = [];
}
} Else

// Case 4: Processing $ (expr, [context]) =$ (content). find (expr)
Return jQuery (context). find (selector );
} Else if (jQuery. isFunction (selector) // The fifth case: Processing $ (function) Shortcut for document ready
Return jQuery (document) [jQuery. fn. ready? "Ready": "load"] (selector );

// Case 6: Process $ (elements)
Return this. setArray (jQuery. makeArray (selector ));
}

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.