jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
if ( typeof target === "boolean" ) {//深度复制
deep = target;
target = arguments[1] || {};
i = 2;
}
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {目标对象的类型不是"object"或者"function"
target = {};
}
if ( length === i ) {//如果只有一个参数传递,扩展jQuery的本身,
target = this;
--i;
}
for ( ; i < length; i++ ) {
if ( (options = arguments[ i ]) != null ) {//只处理非空的值
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
if ( target === copy ) {//防止死循环a{} b{x:a} $.extend(a,b);
continue;
}
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {//合并
//处理深度复制,如果copy存在,并且是纯对象或者数组
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
//进行递归
target[ name ] = jQuery.extend( deep, clone, copy );
} else if ( copy !== undefined ) {
target[ name ] = copy;//直接复制
}
}
}
}
return target;//返回目标对象
};
例:
var a={"height":1,"width":12,"location":{"X":2}};
var b={"height":2,"width":12,"location":{"x":1,"y":1}};
$.extend(a,b);//a={"height":2,"width":12,"location":{"x":1,"y":1}};
$.extend(true,a,b)//深度复制a={"height":2,"width":12,"location":{"X":2,"x":1,"y":1}};
$.extend{a}//扩展$自身