jQuery源代码学习笔记:jQuery.fn.init(selector,context,rootjQuery)代码具体解释

时间:2022-02-06 13:46:39

3.1 源代码

init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined)
//假设selector为空格。!selector为false
if (!selector) {
//此时this为空jQuery对象
return this;
} // Handle $(DOMElement)
//nodeType节点类型。利用是否有nodeType属性来推断是否是DOM元素
if ( selector.nodeType ) {
//将第一个元素和属性context指向selector
this.context = this[0] = selector;
this.length = 1;
return this;
} // The body element only exists once, optimize finding it
//由于body仅仅出现一次。利用!context进行优化
if ( selector === "body" && !context && document.body ) {
//context指向document对象
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
} // Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID? //以<开头以>结尾,且长度大于等于3。这里假设是HTML片段,跳过queckExpr正则检查
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ]; } else {
match = quickExpr.exec( selector );
} // Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
//假设是单独标签
if (ret) {
//假设context是普通对象
if (jQuery.isPlainObject(context)) {
//之所以放在数组中。是方便后面的jQuery.merge()方法调用
selector = [document.createElement(ret[1])];
//调用attr方法。传入參数context
jQuery.fn.attr.call( selector, context, true ); } else {
selector = [ doc.createElement( ret[1] ) ];
} //复杂HTML的处理方法
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
} return jQuery.merge( this, selector ); // HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID //即使是documen.getElementById这样核心的方法也要考虑到浏览器兼容问题,可能找到的是name而不是id
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
} // Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
} this.context = document;
this.selector = selector;
return this;
} // HANDLE: $(expr, $(...))
//没有指定上下文,运行rootjQuery.find()。制定了上下文且上下文是jQuery对象,运行context.find()
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr) //假设指定了上下文。且上下文不是jQuery对象
} else {
//先创建一个包括context的jQuery对象。然后调用find方法
return this.constructor( context ).find( selector );
} // HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
//selector是jquery对象
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
//合并到当前jQuery对象
return jQuery.makeArray( selector, this );
},

当中里面调用的其它jQuery函数待后面再具体学习。

1、当中用到了两个正則表達式:

(1)quickExpr = /^(?

:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;

解释:?:是非捕获组的意思。非捕获组仅仅參与匹配。但不会把匹配到的内容捕获到组里,减少了内存的占用。

[^#<]*匹配除#<以外的随意字符,且出现0次或多次

(<[\w\W]+>):

\w表示匹配字母数字、下划线,\W正好相反,这里匹配的是以字母数字下划线作为第一个字母的一个标签,比方<div>

[^>]*匹配除>之外的全部字符,且出现0次或多次,$结束,表示结束时不能为>字符

#(\w\-]*)$  #id的匹配。id仅仅能为字母、数字、下划线和减号

(2)rsingleTag = /^<(\w+)\s*\/?

>(?:<\/\1>)?$/;

解释:^<(\w+)\s*\/?

>:

^<:以<开头

(\w+):匹配的字母、数字、下划线

\s*:匹配空格符0次或多次,比方能够匹配<div  >这种

\/?>:匹配/符号0次或1次。比方匹配<img    />这种

(?:<\/\1>):\1表示的是前面的(),这里指的就是(\w+),比方前面是<div>。这里就要是</div>

最后的?$表示的是此元素为截止符,要么截止在</div>,要么没有就是前面的<img >或者是<img />

到此就把全部的单独的标签的情况考虑全然了。

学以致用

<script type="text/javascript">
var quickExpr = /^(? :[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/; var match = quickExpr.exec("abc<div>#id");
if (match) {
alert(RegExp.$1)
} var match1 = rsingleTag.exec("<div></div>");
if (match1) {
alert(RegExp.$1);
}
</script>