在实际编程过程,有时候我们会遇到一种情况:当你有一个对象A,在某一个时刻,A已经保存了对应的属性值,而且这些值本身是有效的,这个时候可能需要一个和A完全相同的对象B,并且当B里面的属性值发生变化的时候,A中的属性值不受影响,可以理解为A和B独立,但是B的初始化不是按照我们平时创建该对象的时候的初始化操作,B的初始化数据完全来自A。
一、浅拷贝
当我们需要将一个对象拷贝至另一个对象时,我们一般会这么实现
function shadowCopy(source,target){ var target=target||{}; for(var i in source) { target[i]=source[i]; } return target; } var a={name:'Lily',age:19}; var b=shadowCopy(a);//b={name:'Lily',age:19}
浅拷贝的问题是,如果父对象的属性等于数组或另一个对象,实际上子对象获得的只是一个内存地址,而不是真正拷贝,父对象的数组或对象属性发生变化时,子对象对应属性也发生变化
function shadowCopy(source,target){ var target=target||{}; for(var i in source) { target[i]=source[i]; } return target; } var a={name:'Lily',Hobbies:['Music','Sport']}; var b=shadowCopy(a);//b={name:'Lily',Hobbies:['Music','Sport']} a.Hobbies.push('Read');//b={name:'Lily',Hobbies:['Music','Sport','Read']}
二、深拷贝
为了解决上述问题,需要对对象的数组和对象属性进行深拷贝。它的实现并不难,只要递归调用"浅拷贝"就行了
function deepCopy(source,target){ var target=target||{}; for(var i in source) { if(typeof source[i] === 'object'){ target[i] = (source[i].constructor === Array ) ? [] : {} ; deepCopy(source[i],target[i]); }else{ target[i]=source[i]; } } return target; } var a={name:'Lily',Hobbies:['Music','Sport']}; var b=deepCopy(a);//b={name:'Lily',Hobbies:['Music','Sport']} a.Hobbies.push('Read');//b={name:'Lily',Hobbies:['Music','Sport','Read']},b={name:'Lily',Hobbies:['Music','Sport']}
上述代码中有一个问题,当待拷贝对象中存在自引用时,程序会陷入无限循环
var a={name:'lily'};
a.obj=a;
deepCopy(a);
在Chome Console运行时,如下提示
RangeError: Maximum call stack size exceeded
为了解决自引用问题,拷贝时加入判断逻辑
function deepCopy(source,target){ var target=target||{}; for(var i in source) { //防止自引用 if(source[i] === source ) continue; if(typeof source[i] === 'object'){ target[i] = (source[i].constructor === Array ) ? [] : {} ; deepCopy(source[i],target[i]); }else{ target[i]=source[i]; } } return target; } var a={name:'lily'}; a.obj=a; var b=deepCopy(a);//b={name:'lily'}
三、JQuery拷贝实现
网上有很多对JQuery extend方法的分析,有不了解的可以去搜索阅读
贴一处被分析的源码
jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --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 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 = 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实现疑问
在阅读上述JQuery代码时,有个地方有疑问,疑问代码如下
// Prevent never-ending loop if ( target === copy ) { continue; }
注意到,在extend方法中,为了防止无限循环,这里有一个逻辑,在target对象等于copy对象时,调过这次复制操作。其中,copy对象为options对象的属性对象。
问题是,这里为什么要拿target对象与copy对象比较呢?难道不应该是比较copy对象和options对象吗?
带着这个疑问,在一个已经引入了JQuery库的页面Console中执行下
var a={name:'lily'};
a.obj=a;
var b={};
$.extend(true,b,a);
RangeError: Maximum call stack size exceeded
可以看到,当a对象中存在自引用属性时,extend方法并不能防止无限循环的发生
那么判断target === copy能起到什么作用呢?
var a={name:'lily'};
var b={age:19};
a.obj=b;
$.extend(true,b,a);
//此时b={age: 19, name: "lily"}
去掉判断target === copy会陷入无限循环吗?实际上是不会的
var a={name:'lili'};
var b={age:19};
a.obj=b;
deepCopy(true,b,a);
//b=Object {age: 19, name: "lili", obj: Object}
//其中Object为b
这里的deepCopy是我将JQuery的extend方法,去掉上述判断逻辑,自己实现了一份
function deepCopy() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --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 if ( options === copy ) { continue; } */ // Recurse if we're merging plain objects or arrays if ( deep && copy && ( isPlainObject(copy) || (copyIsArray =isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] =deepCopy( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; var isString=function(obj){ return Object.prototype.toString.call(obj) === '[object String]'; }; var isArray=function(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; }; var isPlainObject=function(obj){ return Object.prototype.toString.call(obj) === '[object Object]'; } var a={name:'lili'}; var b={age:19}; a.obj=b; deepCopy(true,b,a);
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索数组
, 递归
, 对象
属性
javascript 对象拷贝、javascript实例化对象、javascript对象实例、javascript 深拷贝、javascript 深度拷贝,以便于您获取更多的相关知识。