Init Constructor
The previous [overall architecture] has introduced the basic situation of jquery, which mainly introduces the jQuery.fn.init of the entry function of jquery.
Since this function is directly related to the parameters of JQuery (), what parameters can be accepted first. The source code accepts 3 parameters:
Init:function (selector, context, root) {
...
}
jquery (), null parameter, this will return an empty jquery object, return this.
JQuery (selector [, context]), which is a standard and commonly used method, selector represents a CSS selector, which is usually a string, #id or. class, and the context represents the selection range, which is the qualifying function, which can be used for DOM , the JQuery object.
jquery (element|elements), which encapsulates a DOM object or a DOM array into a jquery object.
jquery (jquery object|object) wraps an ordinary object or jquery object in a jquery object.
jquery (HTML [, ownerdocument]), this method is used to convert an HTML string into a DOM object after the creation of a jquery object.
JQuery (HTML, attributes), like the previous method, will bind the methods and properties in attributes to the generated HTML DOM, such as class.
JQuery (callback), this method accepts a fallback function, which is equivalent to the Window.onload method, just relative to. JQuery.fn.init
After the introduction of the entrance, we began to look at the source.
Init:function (selector, context, root) {
var match, Elem;
Processing: $ (""), $ (null), $ (undefined), $ (false)
if (!selector) {
return this;
}
Rootjquery = jQuery (document);
root = Root | | Rootjquery;
Handles HTML string conditions, including $ ("<div>"), $ ("#id"), $ (". Class")
if (typeof selector = = = = "string") {
//This part is split, left behind to speak
//HANDLE: $ (domelement)
} else if (selector.nodetype) {
this[0] = selector;
This.length = 1;
return this;
HANDLE: $ (function)
} else if (Jquery.isfunction (selector)) {
return root.ready!== undefined? Root.ready (s Elector):
//Execute immediately if ready was not present
selector (jQuery);
}
return Jquery.makearray (selector, this);
}
Here are a few things to note, root = root | | Rootjquery, this parameter is not mentioned in the previous description of the usage, this represents document, the default is Rootjquery, and rootjquery = JQuery (document).
As you can see, for handling $ (domelement), it is straightforward to treat jQuery as an array, this[0] = domelement. In fact, it starts with the basic structure of jQuery, after we complete a $ (' Div.span '), and then a JQuery object (this), which gets a set of (a) Dom object, JQuery will add this set of Dom objects as an array element and give a le Ngth. The back is like some chain function operation, if only one DOM operation, such as width, height, only the first element operation, if you can operate on more than one DOM, all the DOM will be manipulated, such as CSS ().
The jQuery idea is as follows, which is a very simple point to implement:
Jquery.prototype = {
//simple point, assuming at this time selector with Queryselectorall
init:function (selector) {
var ele = Document.queryselectorall (selector);
Take this as an array, each of which is a DOM object for
(var i = 0; i < ele.length; i++) {
this[i] = Ele[i];
}
This.length = ele.length;
return this;
},
//css If there is only one object, then take its first DOM object
//If the CSS has two parameters, set CSS
css:function (attr,val) for each DOM object {for
(var i = 0; i < This.length, i++) {
if (val = = undefined) {
if (typeof attr = = = ' object ') {for
(var Key in attr) {
this.css (key, Attr[key]);
}
} else if (typeof attr = = = ' String ') {
return getComputedStyle (This[i]) [attr];
}
} else{
this[i].style[attr] = val;}}
,
}
So for domelement processing, the DOM is assigned directly to the array, return this.
Jquery.makearray is a function that binds an array, as the above principle does, and is discussed later.
Before introducing the following, let's introduce a regular expression that identifies an Html string in JQuery.
var rquickexpr =/^ (?: \ s* (<[\w\W]+>) [^>]*|# ([\w-]+)) $/;
Rquickexpr.exec (' <div> ')//["<div>", "<div>", undefined]
rquickexpr.exec (' <div></ Div> ')//["<div></div>", "<div></div>", undefined]
rquickexpr.exec (' #id ')//["#id", Undefined, "id"]
rquickexpr.exec ('. class ')//null
The above series of regular expression exec, just to illustrate rquickexpr this regular expression after the execution of the results, first, if matched to, if the length of the result array is 3, if matching to ' this HTML, the third element of the array is underfined, if matching to #id, The second element of the array is underfined, or null if no match is reached.
There's also a regular expression:
var Rsingletag = (/^< ([a-z][^\/\0>:\x20\t\r\n\f]*) [\x20\t\r\n\f]*\/?> (?: <\/\1>|) $/i);
Rsingletag.test (' <div></div> ')//true
rsingletag.test (' <div ></div> ')//true
Rsingletag.test (' <div class= ' cl ' ></div> ')//false
rsingletag.test (' <div></ddiv> ')// False
This regular expression is mainly to the HTML string validation, to achieve the effect of error. The Exec and regular expressions are not introduced here much.
Here's a look at the key handling of HTMl strings:
if (selector[0] = = = "<" && selector[selector.length-1] = = = ">" && selector.length >= 3) {//
This is actually an array of forced constructs matching the HTML match = [NULL, selector, NULL];
} else {match = rquickexpr.exec (selector);}
MACTH[1] Limited Html,!context to #id processing if (Match && (match[1] | |!context)) {//HANDLE: $ (HTML), $ (array)
if (Match[1]) {//Exclude context is jquery object Case context = Context instanceof jquery? Context[0]: Context; Jquery.merge is a way to combine arrays specifically for jQuery//jquery.parsehtml is to convert HTML strings to DOM objects jquery.merge (this, jquery.parsehtm
L (match[1], context && context.nodetype? context.ownerdocument | | context:document, TRUE)); HANDLE: $ (HTML, props) if (Rsingletag.test (match[1]) && jquery.isplainobject (context)) {for (match I N context) {//At this time match is not the match if (Jquery.isfunction (This[match])) {This[match] (context[
Match]); ... and otherwise set as atTributes} else {this.attr (match, Context[match]);
}}} return this;
Handle Match (1) for underfined but!context case} else {elem = document.getElementById (match[2]);
if (elem) {//this[0] Returns a standard JQuery object this[0] = Elem;
This.length = 1;
} return this; }//handling the general situation, find actually sizzle,jquery has included it, the following chapter details//Jquery.find () is a jQuery selector, good performance} else if (!context | | context.jq Uery) {return (context | | root). FIND (selector);//handle!context condition} else {//here constructor is actually a return to JQuery
This.constructor (context). Find (selector); }
For NodeType, this is a property of DOM, details Node.nodetype MDN. The value of the nodeType is usually a number, such as 1 means that the dom,3 represents text, etc., or whether the value exists to determine the DOM elements, such as Context.nodetype.
The entire init function, such as the construction logic, is very clear, such as (selector, context, root) three parameters, respectively, the content of the selection, the possible existence of the restricted object or object, and root is the default JQuery (document). Still used in the usual way of jQuery, the handling of each variable is very cautious.
If you look closely at the two parts of the source code, I also added a note, should be able to understand the whole process.
The Find function is actually a Sizzle, and has come out of a separate project, being used directly in jquery, and the Sizzle selector in jquery will be introduced in the next chapter. Through the source code, you can find:
Jquery.find = function Sizzle () {...}
JQuery.fn.find = function (selector) {
...
Reference Jquery.find
jquery.find () ...
}
derived functions
The INIT function still calls a number of jQuery or JQUERY.FN functions, which are analyzed on a case-by-case basis. Jquery.merge
This function, by name, knows what it is used for, merging.
Jquery.merge = function (First, second) {
var len = +second.length,
j = 0,
i = first.length;
for (; J < Len; J + +) {
first[i++] = second[j];
}
First.length = i;
return first;
}
In this way, you can merge types that are similar to arrays and have length parameters, and I feel primarily to facilitate the merging of jquery objects because the jquery object has length. jquery.parsehtml
This function is also interesting to turn a string of HTML strings into DOM objects.
First the function accepts three parameters, the first parameter data is the HTML string, the second parameter is the document object, but to consider the browser compatibility, the third parameter keepscripts is to delete all the script tags in the node, but in parsehtml Surface is not manifested, mainly to buildfragment as a parameter. In summary, the returned object is a DOM array or an empty array.
jquery.parsehtml = function (data, context, keepscripts) {if (typeof data!== "string") {return [];
}//Translation parameter if (typeof context = = = "Boolean") {keepscripts = context;
context = false;
} var base, parsed, scripts; if (!context) {//The meaning of this passage is to create a Document object if the context is missing (support.createhtmldocument) {context =
Document.implementation.createHTMLDocument ("");
Base = Context.createelement ("base");
Base.href = Document.location.href;
Context.head.appendChild (base);
} else {context = document; }}//Used to parse parsed, such as the results of "<div></div>" parsed:["<div></div>", "div"]//parsed[1] = "div
"parsed = rsingletag.exec (data);
Scripts =!keepscripts && [];
Single tag if (parsed) {return [Context.createelement (Parsed[1])];
}//See below for explanation parsed = buildfragment ([data], context, scripts); if (scripts && scripts.length) {jQuery (scripts). Remove ();
} return Jquery.merge ([], parsed.childnodes); }
The Buildfragment function is primarily used to create a fragment object that contains child nodes, which is used for adding and removing nodes of the frequency operation. parsed = Buildfragment ([data], context, scripts), establishes good one fragment object, and uses Parsed.childnodes to obtain the HTML for these data. Jqueyr.makearray
JQuery inside the function call, really is a layer by layer, although sometimes light by the function name, you can know the function, but the logic of thinking is very reference meaning.
Jquery.makearray = function (arr, results) {
var ret = Results | | [];
if (arr! = null) {
if (Isarraylike (Object (arr))) {
jquery.merge (ret, typeof arr = = = "string"?) [arr]: arr);
} else {
Push.call (ret, arr);
}
}
return ret;
}
Makearray merges the left array or string into the right array or a new array, with an introduction to the reference Jquery.merge function.
Next is the Isarraylike function, which may need to consider a variety of factors, such as a compatible browser, and so on, there is a long string:
function Isarraylike (obj) {
//support:real IOS 8.2 only (not reproducible in simulator)
//' on ' check used to PR Event JIT Error (gh-2145)
//Hasown isn ' t used here due to false negatives
//regarding Nodelist length in IE
var length =!! obj && "Length" in obj && obj.length,
type = Jquery.type (obj);
if (type = = = "function" | | jquery.iswindow (obj)) {
return false;
}
return type = = = "Array" | | Length = = 0 | | typeof length = = = "Number" && length > 0 && (length-1) in obj;
}
Summary
This is a connecting link, introduces the more important entry function in JQuery, and then estimates that the next chapter will explain the Sizzle,jquery selectors. Reference
JQuery 2.0.3 Source Analysis Core-Selector
Node.nodetype
Buildfragment of JQuery 3.0