1. jQuery 的深复制
function copy() {
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[ i ] || {};
i++;
}
if ( typeof target !== "object" && !isFunction( target ) ) {
target = {};
}
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
if ( ( options = arguments[ i ] ) != null ) {
for ( name in options ) {
copy = options[ name ];
if ( name === "__proto__" || target === copy ) {
continue;
}
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
src = target[ name ];
if ( copyIsArray && !Array.isArray( src ) ) {
clone = [];
} else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
clone = {};
} else {
clone = src;
}
copyIsArray = false;
target[ name ] = jQuery.extend( deep, clone, copy );
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
return target;
};
$.extend( [deep ], target, object1 [, objectN ] ) (来自:菜鸟教程)
是否深复制、目标对象、被复制的对象
2. 仿写一个自己的
jQuery的extend 方法,支持多个对象,这里实现一个简单的。
function myCopy() {
var target,
copy,
source = arguments[0];
if (!source) {
return source;
}
if ( ( typeof source === "object" ) ) {
target = new A.constructor();
for ( name in source) {
if (!A.hasOwnProperty(name)) {
continue;
}
copy = source[name];
target[ name ] = myCopy( copy );
}
}
else {
target = source;
}
return target;
}
|