$ What is it?-detailed explanation of jquery's $ symbol and init Function

Source: Internet
Author: User
Preface

All the code in this article is from jquery.1.5.2. For ease of understanding, the concept of class is introduced, although jquery is not based on object-oriented thinking.

Jquery is now the most popular JavaScript framework. $ is the most common symbol among them and has been deeply imprinted on jquery.
So what exactly is $?It can accept a single character, a document object, or a function, or call a function.
Next, I will thoroughly analyze the hidden secrets behind this symbol.

Jquery is efficient and refined, especially the simplification of Dom Element Object operations. It frees front-end programmers from a lot of redundant code, greatly improving development efficiency! Compatibility with multiple browsers also maximizes the programmer's ability to get rid of various bugs

$ Is short for element selector. It was first used by the prototype library and abbreviated as getelementbyid. jquery follows this concept and carries forward it, making $ the most distinctive feature of jquery. In jquery, what is the $ symbol?

Anyone familiar with jquery should know that almost all jquery operations start with the $ symbol. When used as an element selector, the operation result returns a jquery object.
Now let's look at the main code of the jquery class constructor.

Constructors of jquery objects
VaR jquery = (function () {// create a jquery object to provide a unified entrance for all jquery methods, avoiding the hassle of recording var jquery = function (selector, context) {// jquery constructor, which calls jquery. FN. init method // returns jquery. FN. return new jquery. FN. init (selector, context, rootjquery );},..... // define the jquery prototype. FN points to jquery. prototype object jquery. fn = jquery. prototype = {// specify the properties of the constructor. FN. initconstructor: jquery, init: function (selector, context, rootjquery ){.....},......}...... // return the jquery variable and define the global variable window. jquery and window. $ points to jqueryreturn (window. jquery = Window. $ = jquery );})();

From the above jquery body structure, we can see that after the first execution is completed,The global variables $ and jquery both point to the VaR jquery = function (selector, context) {} function. Here, we can conclude that $ is the alias of jquery, actually calling jquery. FN. init.

Let's take a look at the VaR jquery = function (selector, context) {} constructor. Why does it not directly return jquery objects? Instead, what about calling another method?

If an object is directly returned, it is inconvenient to use the new jquery object every time. The new operation is directly encapsulated in the jquery constructor, the instantiation operation is simplified. At the same time, jquery unifies the interface through jquery or $ symbol, facilitating code writing, simplifying it, and improving efficiency.

How is the jquery class constructed? It supports various parameter calls.
Let's go directly to jquery. FN. init's "" and jquery's real constructor, so we can fully understand it.

/* All results of searching or generating elements are encapsulated as jquery object arrays and returned. */init: function (selector, context, rootjquery) {var match, ELEM, RET, Doc; // 1) process $ (""), $ (null ), or $ (undefined) // this points to the jquery object if (! Selector) {return this;} // 2) process $ (domelement) // selector. nodetype indicates that it is a DOM element. If it is a DOM element, it is directly put into the jquery object array if (selector. nodetype) {This. context = This [0] = selector; this. length = 1; return this;} // 3) The Body element appears only once. Optimize the search for if (selector = "body "&&! Context & document. body) {This. context = document; this [0] = document. body; this. selector = "body"; this. length = 1; return this;} // 4) if it is a string, there are six cases:/** (1) a single HTML element does not contain the literal volume of the attribute object: createelement + merge * (2) single HTML element with attribute object literal: createelement + ATTR + merge * (3) Multiple HTML elements: buildfragment + merge * (4) # ID without context: getelementbyid or getelementbyid + sizzle * (5) # ID with context: sizzle * (6) experession string: sizzle * (7) Tag selector: S Izzle (built-in getelementbytagname) */If (typeof selector = "string ") {// determine whether it is HTML string or ID // if it is HTML strings match [1] Not empty // if it is ID strings match [1] Null // quickexpr =/^ (?: [^ <] * (<[\ W] +>) [^>] * $ | # ([\ W \-] +) $ )/, match = quickexpr.exe C (selector); // analyze the matching result, and when # ID does not have the context parameter, for example, not $ ('# XXX', XXX) if (match & (Match [1] |! Context) {// process HTML characters $ (HTML)-> $ (array) if (Match [1]) {// If context is a jquery object, use the first element, that is, context [0] context = context instanceof jquery? Context [0]: context; // obtain the document DOC = (context? Context. ownerdocument | context: document); // determines whether a single element string ret = rsingletag.exe C (selector); // If (RET) {// check whether the context contains the object attributes. Applicable scenarios include $ ('<div>', {'id': 'test ', 'class': 'test'}); If (jquery. isplainobject (context) {selector = [document. createelement (Ret [1])]; jquery. FN. ATTR. call (selector, context, true);} else {// without the object literal volume // for example $ ('<div>') selector = [Doc. createelement (Ret [1] )] ;}} Else {// if it is a string of multiple elements, for example, $ ('<div> <A> </a> </div>') ret = jquery. buildfragment ([Match [1], [Doc]); selector = (Ret. cacheable? Jquery. clone (Ret. fragment): Ret. fragment ). childnodes;} // combines the generated result selector into the jquery object. Return jquery. merge (this, selector); // process $ ("# ID"), for example, $ ("# XXX");} else {ELEM = document. getelementbyid (Match [2]); If (ELEM & ELEM. parentnode) {// handle bugs that confuse IE and opera ID with name, and use sizzle to find if (ELEM. ID! = Match [2]) {return rootjquery. find (selector);} // otherwise, insert the jquery object array this. length = 1; this [0] = ELEM;} This. context = document; this. selector = selector; return this;} // process $ (expr, $ (...)), search by sizzle, such as $ ("Div"), $ ('div> A'), $ ('div, A'), $ ('div: First ')} else if (! Context | context. jquery) {return (context | rootjquery ). find (selector); // processing: $ (expr, context), for example, $ ('div A'); or $ ('A', 'div ') or $ ('div '). find ('A');} else {return this. constructor (context ). find (selector);} // 5) Processing: $ (function), set the function bound when the Dom is loaded, equivalent to $ (). ready () {Foo} else if (jquery. isfunction (selector) {return rootjquery. ready (selector);} // 6) Processing: $ (...)), complete the simple parameters of the cloned jquery object, and complete the IF (SE Lector. selector! = Undefined) to add {This. selector = selector. selector; this. context = selector. context;} // use makearray to add elements to the jquery object, for example, $ ([1, 2]); Return jquery. makearray (selector, this );},

From the source code, we can see that jquery calls various parameters through various condition judgments and powerful regular expressions.

Summary

$ Is actually a reference to the jquery class constructor. This function actually calls jquery. FN. init (jquery. prototype. init) to generate the jquery object, where jquery. all prototype methods are inherited by jquery objects. $. Func is actually a static method of the jquery class, so $ is the constructor of the jquery class. It supports searching and generating various conditions and returning DOM objects to form a jquery object. It is also a class, is the entry to all jquery static methodsFor example, you can use $. Ajax ().

Finally, we will provide you with some resources and 14 skills to improve jquery code.
For details about the jquery sizzle selector, refer to the introduction to the jquery sizzle 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.