Home  >  Article  >  Web Front-end  >  Analysis of jQuery’s operating mechanism and design concepts_jquery

Analysis of jQuery’s operating mechanism and design concepts_jquery

WBOY
WBOYOriginal
2016-05-16 18:08:401015browse

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

When some developers use jQuery, they often encounter many problems because they only know how to use it in the jQuery document and do not understand how jQuery operates. Most of these problems are caused by improper use, and a few are jQuery bugs. If we don't understand its operating mechanism and core source code, it will be difficult for us to write high-performance programs based on the jQuery class library.

When debugging a program based on jQuery, most of the time we have to track the jQuery object to analyze its running status. However, the jQuery code is not as standard as Ext and YUI. Its code is a bit obscure. Difficult to understand. In other words, if you want to use jQuery well, you must know its source code.

The design concept of jQuery

Before using jQuery, we all ask what is jQuery? jQuery is a class library that, like prototype, mootools and other class libraries, provides auxiliary functions for JavaScript development on the Web. So why choose jQuery? Before jQuery appeared, Prototype and YUI were both very mature JS frameworks, and each had its own characteristics. Why abandon them and use the rising star jQuery? What excellent features does it have to attract developers?

To answer this question, we have to understand the design concept of jQuery. Recall or imagine, how do 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 is obtained or set, and innerHTML is used to obtain or set its content, or to monitor events (such as click). In terms of controlling style, We will change height, width, display, etc. to achieve visual effects. For Ajax, we also get data and add content to a certain element on the page.

In summary, we are operating on DOM elements. This element may be one or more. This element may be a Document, Window or DOM element. In this way, our tasks are two parts, one is to find DOM elements, and the other is to operate on DOM elements.

For those who are more proficient in using it, it is not difficult to use direct search methods such as getElementById or indirect search methods such as Element.lastChild. For DOM elements, DOM operations are also very rich. , is it not difficult to use? So what is the use of the class library? The most difficult issue is browser compatibility. All JavaScript frameworks must solve this problem and simplify the operations of JavaScript itself.

Prototype can be said to have pioneered the JS class library, giving us a refreshing feeling. It solves most browser compatibility issues. At the same time, it simplifies the problem of frequent writing errors when the original function name is long and difficult to remember (use $(xx) instead of getElementById), provides Ajax access method, and extends JavaScript native objects such as Array, Object, Function, and Event.

But these still cannot meet the needs of development. For example, searching for DOM elements in the DOM tree can only be done by the ID of the element, but we want a more convenient search method and also hope to have a unified The entrance should not be too general, the learning curve is too high or difficult to use.

jQuery starts from here and unifies everything in jQuery objects. Using jQuery means using jQuery objects. In fact, jQuery's pioneering work is exactly as its name suggests: query. Its powerful search capabilities put all frameworks to shame. jQuery is essentially a query. Based on the query, the function of operating on the found elements is also provided. In this way, jQuery is the unification of query and operation. The query is the entry and the operation is the result.

The implementation of jQuery can also be divided into two parts. One part is the static method of jQuery, which can also be called a utility method or tool method, and is directly referenced through the jQuery namespace of jQuery.xxx(). The second part is the jQuery instance method, which is a method to generate a jQuery instance through jQuery(xx) or $(xx), and then reference it through this instance. Most of the methods in this part use static method proxies to complete functions. Real functional operations are implemented in jQuery's static methods. These functions can be broken down into the following parts:

1. Selector, find elements. This search not only includes the CSS Selector function based on CSS1~CSS3, but also includes some functions extended to direct search or indirect search.

2. Attribute operations of Dom elements. Dom elements can be regarded as html tags, and the operation of attributes is to operate on the attributes of the tag. This attribute operation includes adding, modifying, deleting, taking values, etc.

3. CSS style operation of Dom elements. CSS controls the display of the page. The operation of CSS must include height, width, display and other commonly used CSS functions.

4. Ajax operation. The function of Ajax is to fetch data from the server asynchronously and then perform related operations.

5. Event operation. The compatibility of Events has been unified.

6. Animation (Fx) operation. It can be seen as an extension of CSS styles.

Construction of jQuery object

Generating or building a jQuery object is actually building and running a query (selector). Since it is a query, the results (DOM elements) will definitely be searched, and then these results will be operated on. So where are the results of these searches stored? The best place is of course inside this jQuery object. The result of the search may be one element, or it may be multiple elements such as (in the form of a collection of NodeSet). In other words, there is a collection inside the jQuery object. This collection stores the found DOM elements.

But the jQuery object mentioned in the previous section is the unified entrance for all operations, so its construction cannot only be limited to finding DOM elements from DOM documents, but may also be transferred from other collections. The Dom element that comes over may also be a DOM element generated from an HTML string.

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

A few examples:

1. $($("P")) can be seen that its parameters can be jQuery objects or a collection of ArrayLike.

2. $() is the abbreviation of $(document).

3. $(3) will put 3 into the jQuery object collection.

For elements such as $(3) (such as elements of the ArrayLike collection) that are not DOM elements, it is best not to construct jQuery objects. The methods of jQuery objects are all targeted at DOM objects. If you don't know how to use it, it may lead to errors. Having said so much above, it is still difficult to understand its principle. Let’s analyze it in detail from the perspective of source code:

No object is generated through the call of jQuery(xxx), and its this points to the Window object. So how are jQuery’s instance methods inherited? Take a look:

var jQuery = window.jQuery = window.$ = function(selector, context)
{ return new jQuery.fn.init(selector, context);
};
This is the general entrance of jQuery. The jQuery object actually inherits the methods in its prototype through new jQuery(). The jQuery object is actually an object generated by the jQuery.fn.init function. Here we can see that it does not make much sense to add some function set objects to jQuery.prototype. Because our new jQuery() is OK, but the generated jQuery object will be discarded when returned. So it's best not to use new jQuery() to build jQuery objects. The jQuery object is actually new jQuery.fn.init. Then jQuery.fn.init.prototype is the operation method of jQuery object. For example,

jQueryjQuery.fn.init.prototype = jQuery.fn;
Sometimes you may worry about implementing the function on line 589 and putting the functions in jQuery.fn into jQuery.fn.init.prototype. , then what should I do through the jQuery.fn.extend method? This is actually a reference to jQuery.fn. When extending jQuery, just extend the relevant functions to jQuery.fn. Now let’s take a look at how jQuery.fn.init does its job:

Copy the code The code is as follows:

init : function(selector, context) {
selectorselector = selector || document;// Make sure the selector exists

// The first case is Handle $(DOMElement) 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.exec(selector);
if (match && (match[1] || !context)) {
if (match[1])// The second case is handled $(html) -> $(array)
selector = jQuery.clean([match[1]], context);
else {// The third case: HANDLE: $("#id")//Processing $("#id")
var elem = document.getElementById(match[3]);
if (elem) {
// IE will return the element with name=id. If so, document.find(s)
if (elem.id != match[3])
return jQuery().find(selector) ;
// Build a new jQuery(elem)
return jQuery(elem);
}
selector = [];
}
} else

// The fourth case: processing $(expr, [context])==$(content).find(expr)
return jQuery(context).find(selector);
} else if (jQuery. isFunction(selector)) //The fifth situation: processing $(function)7Shortcut for document ready
return jQuery(document)[jQuery.fn.ready ? "ready" : "load"](selector);

// The sixth case: processing $(elements)
return this.setArray(jQuery.makeArray(selector));
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn