`

jQuery源码分析—2代码整体结构与核心方法

 
阅读更多

该内容转自http://nuysoft.iteye.com/blog/1182087,笔者做了部分修改

 

去除掉jQuery变量和扩展方法,先看以下精简代码

 

 

(function( window, undefined ) {
	
// 构造jQuery对象
var jQuery = (function() {

//以下定义了内部变量
// Define a local copy of jQuery

var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	};

//把jQuery的原型 prototype赋给jQuery.fn
jQuery.fn = jQuery.prototype = {
	constructor: jQuery,
	/**
	 * selector有以下7种分支情况:
       DOM元素
       body(优化)
       字符串:HTML标签、HTML字符串、#id、选择器表达式
       函数(作为ready回调函数)
       最后返回伪数组
	 */
	init: function( selector, context, rootjQuery ) {
	   //后期会详细分析此处的实现
	}
	
};

// Give the init function the jQuery prototype for later instantiation
//把jQuery.fn赋值到jQuery.fn.init.prototype,这样init指向的原型prototype也具有了jQuery.fn的功能
jQuery.fn.init.prototype = jQuery.fn;

//jQuery的继承实现
jQuery.extend = jQuery.fn.extend = function() {

};

// 在jQuery上扩展静态方法
jQuery.extend({
	// ready bindReady
   // isPlainObject isEmptyObject
   // parseJSON parseXML
   // globalEval
   // each makeArray inArray merge grep map
   // proxy
   // access
   // uaMatch
   // sub
   // browser
});

// 到这里,jQuery对象构造完成,后边的代码都是对jQuery或jQuery对象的扩展
return jQuery;

})();

// Expose jQuery to the global object
//设置jQuery 和  $为window全局变量
window.jQuery = window.$ = jQuery;


})( window );

 

 

下面分析框架中的代码

 

1、 

jQuery对象不是通过 new jQuery 创建的,而是通过 new jQuery.fn.init 创建的

 

var jQuery = function( selector, context ) {

       return new jQuery.fn.init( selector, context, rootjQuery );

}

jQuery对象就是jQuery.fn.init对象。如果执行new jQeury(),实际上在闭包中执行new jQuery.fn.init,最后返回 jQuery.fn.init对象;代码中通过

window.jQuery = window.$ = jQuery;

设置jQuery 和  $为window全局变量,而jQuery为函数对象,因此可以直接调用jQuery( selector, context );来返回jQuery对象(函数)。这里顺便说一下,对于给window对象增加属性或方法,实际上是全局的,可以直接访问,比如如下代码

 

window.method1 = function(){console.info('全局方法')}; window.method1();//全局方法 method1();//全局方法

 

2、

代码中先执行 jQuery.fn = jQuery.prototype,再执行 jQuery.fn.init.prototype = jQuery.fn,合并后的代码如下:

 

jQuery.fn.init.prototype = jQuery.fn = jQuery.prototype

 

所有挂载到jQuery.fn的方法,相当于挂载到了jQuery.prototype,即挂载到了jQuery 函数上(一开始的jQuery = function( selector, context ) ),但是最后都相当于挂载到了 jQuery.fn.init.prototype,即相当于挂载到了一开始的jQuery 函数返回的对象上,即挂载到了我们最终使用的jQuery对象上。

 

 

 

 3、jQuery.fn.init

jQuery.fn.init的功能是对传进来的selector参数进行分析,进行各种不同的处理,然后生成jQuery对象。

 

 

类型(selector

处理方式

DOM元素

包装成jQuery对象,直接返回

body(优化)

document.body读取

单独的HTML标签

document.createElement

HTML字符串

document.createDocumentFragment

#id

document.getElementById

选择器表达式

$(…).find

函数

注册到dom ready的回调函数

 

 

 4、jQuery.extend = jQuery.fn.extend

//jQuery的继承实现
/**
 * 合并两个或更多对象的属性到第一个对象中,jQuery后续的大部分功能都通过该函数扩展
 	通过jQuery.fn.extend扩展的函数,大部分都会调用通过jQuery.extend扩展的同名函数
  	如果传入两个或多个对象,所有对象的属性会被添加到第一个对象target
  	如果只传入一个对象,则将对象的属性添加到jQuery对象中。
	用这种方式,我们可以为jQuery命名空间增加新的方法。可以用于编写jQuery插件。
	如果不想改变传入的对象,可以传入一个空对象:$.extend({}, object1, object2);
	默认合并操作是不迭代的,即便target的某个属性是对象或属性,也会被完全覆盖而不是合并
	第一个参数是true,则会迭代合并
	从object原型继承的属性会被拷贝
	undefined值不会被拷贝
	因为性能和安全原因,JavaScript自带类型的属性不会合并
	例如:
	jQuery.extend( target, [ object1 ], [ objectN ] )
	jQuery.extend( [ deep ], target, object1, [ objectN ] )
 */
jQuery.extend = jQuery.fn.extend = function() {
	var options, //传入的参数
		name, //参数中的属性
		src, //源
		copy, //待copy的对象或变量
		copyIsArray, //copy的是否为数组
		clone,//深层copy时,调整中间变量
		target = arguments[0] || {},//要copy到的目标
		i = 1,
		length = arguments.length,
		deep = false;//是否深度copy

	// Handle a deep copy situation
	//如果第一个参数为布尔型,则处理深层次copy
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		// 跳过boolean和target,从第3个开始传入的参数开始
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	// target不是对象也不是函数,则强制设置为空对象
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	// 如果只传入一个参数,则认为是对jQuery扩展
	if ( length === i ) {
		target = this;
		--i;//此时i取第一个参数
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		// 只处理非空参数
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				// 避免循环引用,即target和要copy的是同一对象
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				// 深度拷贝且值是纯对象(json对象)或数组,则递归
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {//如果是数组
						copyIsArray = false;
						//注意此处的写法,由于&&是返回第二个表达式的值,故可以分解成以下情况
						//1、src为null或undefined时,clone为[]
						//2、src为数组时,则直接返回src赋给clone
						//3、src为非数组时,则clone为[]
						//这种写法确保clone为数组,如果target[ name ]为非数组时,copy就会用数组覆盖原来的值
						clone = src && jQuery.isArray(src) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}

					// Never move original objects, clone them
					// 递归调用,深copy
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};
 

关于jQuery中extend方法的具体分析参见代码中的注释,从代码中可以看出jQuery中的extend是实现了对象间的copy功能,更像ext中的apply方法,只是比ext中的apply强大多了。而ext中的extend方法更像是面向对象中类继承,主要对function实现了继承,包括属性和方法的继承,可以重构,也可以继承。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics