JQuery method source code parsing--jquery ($) method (i)

Source: Internet
Author: User

JQuery method source code parsing--jquery ($) method

Note:
1. This article analyzes the code is jquery.1.11.1 version, the official web download uncompressed version can
2. Please specify the source of the reprint

jquery Method:
This method everyone is not unfamiliar, in the course of use, it also has another name, dollar sign: $,$ (...) is actually jquery (...); It has many uses, usually returning a jquery object, or as a $ (document). Ready (...); Short form, look at the use of jquery before the analysis.
1.jQuery (selector [, context]) selector:string;context:element or JQueryReturns a JQuery object in context that conforms to the selecttor expression, with the context default of $ (document), and if no natural return is found for an empty jquery object, which is the jquery object with length 0;
eg:$ ("Div.foo"). Click (function () {
$ ("span", this). AddClass ("Bar");
});
2.jQuery (Element), jquery (Elementarray) Element:ElementelementArray:Array of element transforms (wraps) DOM elements or arrays into a JQuery object. PS: From the principle of implementation, it is more appropriate to call packaging.
eg:$ (document), $ (this), $ (document.getElementsByTagName ("div"));
3.jQuery (object) Object:plainobject a normal object into a JQuery object, ordinary object: Plainobject, is an object with only key-value pairs; what's the use?! Temporarily not understand, the official website gives explanation:At present, the only operations supported on plain JavaScript objects wrapped in JQuery is:
. data (),. Prop (),. On (),. Off (),. Trigger () and. Triggerhandler ().
The use of. Data (or any method requiring. Data ()) on a plain object would result in a new
Property on the object called Jquery{randomnumber} (eg. jQuery123456789).
4.jQuery (selection) selection:jquery copy a JQuery objectWhen a JQuery object was passed to the $()function, a clone of the object is created.This new JQuery object references the same DOM elements as the initial one.
5.jQuery () returns an empty JQuery object
6.jQuery (HTML [, ownerdocument]) html:htmlStringownerDocument:document creates a new DOM element, and the second parameter specifies the document used to create the element; The second element may be used when there are multiple IFRAME scenarios
eg:$ ("<p id= ' test ' >my <em>new</em> text</p>"). AppendTo ("body");
7.jQuery (HTML, attributes) Html:htmlstring, this scenario must be a single-label attributes:plainobject, an object that describes element properties in the form of a key-value pair eg:$ ("<div> </div> ", {
"Class": "My-div",
On: {
Touchstart:function (event) {
Do something}
}}). AppendTo ("body");

If the second object's property name is a function (and possibly an intrinsic function) in jquery, the function is called, and the property value is treated as a parameter. If the attributes is too complex, the individual does not recommend such writing, written as follows is more clear.
$ ("<div></div>")
. addclass ("My-div")
. On ({
Touchstart:function (event) {
Do something
}
})
. AppendTo ("body");

8.jQuery (callback) Callback:function There's nothing to say, it's $ (document). Short form of Ready (callback).What is jQuery Object??
The jquery method, which usually returns a JQuery object, first we have to know exactly what the jquery object is and what it looks like.
Write a few li:<body> in HTML
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
</body>
Create a jquery object and output it:
Console.log ($ ("Li"));
Run the following in Chrome:

You can see that the jquery object has the structure of an array of classes, with an index of 0 to length-1 and a length attribute (but no array of concat or slice, etc.), and each li is the element Dom object. The structure of this class of arrays can be thought of as a native JS object array, in addition to the structure of this class array, the other is some jquery properties and methods, open the implicit pointer to prototype, you can see many of our common jquery methods.
Summing up, jquery object, is on the basis of the JS object, packaging some of the objects of the jquery method, there is an English word to describe the more appropriate, is wrap (parcel).
the structure of the jquery method

In the source code of jQuery1.11.1, search jquery, in the source code is not far from the beginning, you can see the following codes:
Define a local copy of JQuery
JQuery = function (selector, context) {
The JQuery object is actually just the Init constructor ' enhanced '
Need init if JQuery is called (just "allow" error to being thrown if not included)
return new JQuery.fn.init (selector, context);
}
As you can see, jquery is a function that returns an object.
= =, what?! Actually returned is a JQuery.fn.init object?!

Let's search the JQuery.fn.init: init = jQuery.fn.init = function (selector, context) {
var match, Elem; ......};
At the end of this function, the following code is coming (the locations of the different versions of the code are not necessarily the same, or the search is more reliable)://Give the INIT function The JQuery prototype for later instantiation
Init.prototype = Jquery.fn;

Then search "Jquery.fn =", you can see Jquery.fn = Jquery.prototype = {...}; This is clear, Jquery.fn is the prototype of the function of jQuery, and Init.prototype = Jquery.fn, that is to say:
JQuery.fn.init.prototype = Jquery.prototype
Then through the jQuery.fn.init.prototype of this function constructed object, you can point to the JQuery.fn.init.prototype reference, find jquery prototype method, in a sense, through the jquery.fn.i The method that nit constructs is the jquery object.
To summarize, the construction of JQuery objects is actually achieved through jQuery.fn.init, through Init.prototype = Jquery.prototype, Enables the JQuery.fn.init object to use the Jquery.prototype method property. Jquery.init Method
Before parsing the Init method, you must recognize the two regular expressions used by the method: first://A simple way to check for HTML strings
Prioritize #id over <tag> to avoid XSS via Location.hash (#9521)
Strict HTML Recognition (#11290: Must start with <)
rquickexpr =/^ (?: \ s* (<[\w\W]+>) [^>]*|# ([\w-]*)) $/
As you can see from the comments, this is a regular expression that matches the HTML, because of the reason for a bug, but also to match the string in the form of #id, to take precedence.
/^(...) $/--> wraps the start and end locators, matching the entire string; (?: ...) ----to indicate that this grouping does not capture, just the role of grouping, can improve performance; \s* (<[\w\w]+>[^>]*) matches a string of <tag> that can start with a blank character and can end with any non-' > ' # ([\w-]*)-Match a string that starts with # followed by any letter or minus sign
The whole translation is a string that matches the form of <tag> or #id.
Execute: rquickexpr =/^ (?: \ s* (<[\w\W]+>) [^>]*|# ([\w-]*)) $/;
Console.log (Rquickexpr.exec ("<tag>")); output: ["<tag>", "<tag>", Undefined, index:0, input: "<tag > "]

Another regular: var Rsingletag = (/^< (\w+) \s*\/?> (?: <\/\1>|) $/);
The name can be guessed, this is the form of a matching single label.
< (\w+) \s*\/?>---match a label to make <tag> or <tag/> form (?: <\/\1>|)-->\1 represents the string captured in group 1, That is, match the same closed tag as before </tag> or an empty string (note that the following or symbol does not follow, or is an empty string)
Together is a match <tag/> or <tag></tag>; is not difficult to find, this regular match <tag attr= "..." ></tag> this single label with attributes, also can't match <tag>asdf</tag> the label with the text node, which, to be exact, matches only the empty label of the single.
The jquery method can be said to be the most central method of JQ, and it is implemented by the Init method, then it is not very long?! Not really, just 100 lines, because it also calls the other methods of jquery, the following single on this init method structure, analysis.
Direct Search JQuery.fn.init, will soon be able to find the source of the Init function, roughly a bit, found a lot of if else, which is the function of jquery, a variety of functions in line with; Write a comment directly in the code to parse the code
init = JQuery.fn.init = function (selector, context) {var match, Elem;               Handles the jquery () Form, returning an empty jquery object//HANDLE: $ (""), $ (null), $ (undefined), $ (false) if (!selector) {          return this; }//Handle HTML strings/* #源码分析 * Match HTML (start with <, end with >, or <tag> ...)  form, recommended to write strict HTML), or #id form, and make sure that #id情况下, no context */if (typeof selector = = = "string") {if (Selector.charat (0) = = = "<" && Selector.charat (selector.length-1) = = = ">" && selector.length &                    Gt;= 3) {/* #源码分析 * Assume that the string htmlstring with the beginning of <, ending with > and longer than 3, is then saved to match *///Assume that strings, start and end with <> is HTML and skip the regex chec               K match = [null, selector, NULL];               } else {match = rquickexpr.exec (selector); }/* #源码Analyze *what is match?               * We have analyzed the rquickexpr regular expression, which has two groupings (the outermost group is not captured, not counted), * this way, if the Exec method is matched, you should return an array of length 3, including the index and input properties.               * Then match[0] is the whole matching array, match[1] is the matching <tag> tag (if any), match[2] Match #id (if any) * obviously match[1],match[2] can only have one captured               *//Match HTML or make sure no context are specified for #id if (Match && (match[1] | |!context)) {//process jquery (HTML [, Ownerdocument]), based on HTML  Generates a DOM element that returns a jquery object, just like the following comment $ (HTML), $ (array)//match[1]//HANDLE: $ (HTML), $ (array) if (Match[1]) {/* #源码分析 * If the context is a jquery object,                         Convert to JS native object. * As we said, the jquery object is the object that wraps some methods to JS native object, and the native object exists in jquery in the form of an array of classes, * so Context[0] is the first native object in the JQuery object, where the CO      ntext expected to pass in the document or $ (document) */                   Context = Context instanceof JQuery?                        CONTEXT[0]: Context; /* #源码分析 * This calls the Jquery.parsehtml method, which is to convert htmlstring to DOM array * also called Jquery.merge (fi Rst,second), receive two "class array" parameters, * This method is to append the second array to the end of the first array, will change the first array * before, the jquery object has the class                         The array structure, which currently does not operate this, its length = 0 * So the following code is to convert the htmlstring into a DOM array and append to the end of this. *///Scripts is true for Back-compat//intentionally let the error being th                              Rown If parsehtml is not a present jquery.merge (this, jquery.parsehtml ( MATCH[1], context && Context.nodetype? context.ownerdocument | |                                                 Context:document, True)); /* #源码分析 * processing jquery (HTML, AttriButes) This usage * The first argument must be a single label, the second parameter is a normal object, similar to {html: "Hello World", ID: "Test"} * Note                         , in this case, will go above the branch, has changed the single label to the DOM and stitching it into the "* *///HANDLE: $ (HTML, props)                              if (Rsingletag.test (match[1]) && jquery.isplainobject (context)) { For (match in context) {/* #源码分析 * The match here is Contex Properties of T * If there is a match method, the match method will be called * e.g. {html: "Hello World", I                                   D: "Test"}, will call this.html ("Hello World") method * Otherwise by property processing */                                   Properties of the context are called as methods if possible                         if (Jquery.isfunction (this[match])) {this[match] (context[match]);           ... and otherwise set as attributes} else {                                   This.attr (match, context[match]);                   }}} return this;                    /* #源码分析 * processing match[2] is captured, that is, the situation of #id *//HANDLE: $ (#id)                         } else {elem = document.getElementById (match[2]); Check parentnode to catch when Blackberry 4.6 Returns//nodes that is no longer in the Docume  NT #6963//In order to be compatible with a bug in BlackBerry 4.6, not only the element is judged, but also the Elem.parentnode if (                              Elem && Elem.parentnode) {//Handle the case where IE and Opera return items By name instead of ID/* #源码Analysis * Early IE's document.getElementById () bug, when looking for elements, the form of the element name is also considered an ID,                              * This time using the Find method to be compatible, search for "rootjquery =", you will find Rootjquery = jQuery (document); */if (elem.id!== match[2]) {return rootjquery.find (SE                              Lector);                              }/* #源码分析 * Otherwise put directly in this[0] * * Otherwise, we inject the element directly into the JQuery object thi                              S.length = 1;                         This[0] = Elem;                         } this.context = document;                         This.selector = selector;                    return this;            }/* #源码分析 * Processing $ (case of complex selectors), using the Find method to process and return, * Here are two else judgments, just to make sure that the jquery object calls the Find method,   * If the context is not a jquery object, use constructor to construct a *context.jquery-->jquery is a version attribute on Jquery.fn, which is used here to determine if it is a jquery object.               *///HANDLE: $ (expr, $ (...))               } else if (!context | | context.jquery) {return (context | | rootjquery). FIND (selector); HANDLE: $ (expr, context)//(which is just equivalent to: $ (context). Find (expr)} els               e {return This.constructor (context). Find (selector); }/* #源码分析 *else selector is not a string type *///HANDLE: $ (domelement)} else if (SE               Lector.nodetype) {/* #源码分析 * processing $ (domelement) Form, this is relatively simple, is added to This[0] */               This.context = this[0] = selector;               This.length = 1;          return this;      HANDLE: $ (function)//Shortcut for document ready} else if (Jquery.isfunction (selector)) {        /* #源码分析 *$ (function), which is called $ (document). Ready () method */Return typeof ROOTJ                    Query.ready!== "undefined"? Rootjquery.ready (selector)://Execute immediately if ready was not present select          or (jQuery); }/* #源码分析 * If selector.selector!== undefined, then selector itself may be a jquery object, do the following processing, why?!               Do not know */if (selector.selector!== undefined) {this.selector = Selector.selector;          This.context = Selector.context;          }/* #源码分析 *jquery.makearray (arr) is to convert an array of classes into a pure array form, as the API says.          * Actually Makearray has a second parameter, but only for internal use, which is the case now *jquery.makearray (arr, results)--Append the arr array to the results tail by calling Jquery.merge * This will deal with jquery (Elementarray), jquery (object) in both cases */return Jquery.makearray (selector, this); };


Upcoming AnnouncementsAfter analysis, we probably have a general understanding of the function of jquery, which also calls the other jquery tool functions:such as Jquery.merge, jquery.parsehtml, Jquery.isplainobject, find, $ (document). Ready (), Jquery.makearray methodThe next article on the above methods to choose a few simple analysis, too complex, first put it.

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.