jQuery.fn.init分析 - make it easy      

Zhenyi's blog

jQuery.fn.init分析

    

jQuery.fn.init对象分析,代码如下:(v1.9.1)

init: function( selector, context, rootjQuery ) {
	var match, elem;

	// 如果传入的值是$(""), $(null), $(undefined), $(false),直接返回jQuery对象
	if ( !selector ) {
		return this;
	}

	// 传入的是一个字符串
	if ( typeof selector === "string" ) {
	
		//传入的是一个html字符串
		if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
			
			match = [ null, selector, null ];
		} 
		//判断选择器是不是id,rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/
		else {
			match = rquickExpr.exec( selector );
			//比如如果传入#test,match = ['#test',undefined.'test']
		}

		//如果是html字符串 或者是 id选择器
		if ( match && (match[1] || !context) ) {

			// HANDLE: $(html) -> $(array)
			
			//传入的是html字符串
			if ( match[1] ) {
			
				//是否有传入父选择器,如果没有  context 为undefined,有则转化为jQuery对象
				context = context instanceof jQuery ? context[0] : context;

				// 生成jquery对象
				jQuery.merge( this, jQuery.parseHTML(
					match[1],
					context && context.nodeType ? context.ownerDocument || context : document,
					true
				) );

				// HANDLE: $(html, props)
				if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
					for ( match in context ) {
						// Properties of 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;

			//传入的是id选择器
			} else {
				// document.getElementById
				elem = document.getElementById( match[2] );

				//该元素是否存在
				if ( elem && elem.parentNode ) {
					
					//处理兼容性,ie等浏览器用name代替id
					if ( elem.id !== match[2] ) {
						return rootjQuery.find( selector );
					}

					//已经找到元素,则给jquery加上属性
					this.length = 1;
					this[0] = elem;
				}

				this.context = document;
				this.selector = selector;
				return this;
			}

		// 处理: $(expr, $(…)),丢给sizzle
		} else if ( !context || context.jquery ) {
			return ( context || rootjQuery ).find( selector );

		// 处理: $(expr, context),丢给sizzle
		// (which is just equivalent to: $(context).find(expr)
		} else {
			return this.constructor( context ).find( selector );
		}

	// 处理: $(DOMElement),传入的已经是dom对象
	} else if ( selector.nodeType ) {
		this.context = this[0] = selector;
		this.length = 1;
		return this;

	// 处理: $(function),传入的是function,注册到jQuery.ready()里面
	} else if ( jQuery.isFunction( selector ) ) {
		return rootjQuery.ready( selector );
	}

	if ( selector.selector !== undefined ) {
		this.selector = selector.selector;
		this.context = selector.context;
	}
	//返回伪数组
	return jQuery.makeArray( selector, this );
},

总的来说有以下状况:

  • HTML标签
  • id
  • 选择器表达式
  • HTML字符串
  • DOM元素 +函数

都不满足的,最后生成一个数组返回