jQuery源码分析10: jQuery.extend

jQuery源码分析10: jQuery.extend

Description: Merge the contents of two or more objects together into the first object.
用法:
jQuery.extend( target, [ object1 ], [ objectN ] )
jQuery.extend( [ deep ], target, object1, [ objectN ] )

jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;

//< 首先判断argument[0]是否是true/false,若是,则表示进行递归或非递归扩展
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}

//< 当target是非对象,而且也不是函数时重置 target={};
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}

//< 如果没有target则默认扩展jQuery对象
if ( length === i ) {
target = this;
--i;
}

//< 遍历argument中要合并的对象将其合并到target中
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
if ( target === copy ) {
continue;
}

// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
//< 重置copyIsArray,以便对下一个参数arguments[i+1]重新判断
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}

// Never move original objects, clone them
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算法描述:
若typeof argument[0] === 'Boolean'时,则从第二个参数开始考虑;
若argument[0]判断完成且此时arguments中除此以外只有一个参数,则默认target指向jQuery对象,即默认扩展jQuery对象;
若target是非对象,而且也不是函数时重置 target={};
遍历object1[, ..., objectN]将每一个对象中的所有属性都copy到target中同名属性中.
src = target[ name ];
copy = options[ name ];
若deep && copy === true则:
若jQuery.isPlainObject(copy)===true,则clone=src&&jQuery.isPlainObject(src)?src:{};
若jQuery.isArray(copy)===true,则clone=src&&jQuery.isArray(src)?src:[];
然后递归调用target[name]=jQuery.extend(deep,clone,copy);
否则,target[name]=copy;

你可能感兴趣的:(jquery)