在javascript中,对对象进行拷贝的场景比较常见。但是简单的复制语句只能对对象进行浅拷贝,即复制的是一份引用,而不是它所引用的对象。而更多的时候,我们希望对对象进行深拷贝,避免原始对象被无意修改。
对象的深拷贝与浅拷贝的区别如下:
浅拷贝:仅仅复制对象的引用,而不是对象本身;
深拷贝:把复制的对象所引用的全部对象都复制一遍。
一. 浅拷贝的实现浅拷贝的实现方法比较简单,只要使用是简单的复制语句即可。
1.1 方法一:简单的复制语句/* ================ 浅拷贝 ================ */
function simpleclone(initalobj) {
var obj = {};
for ( var i in initalobj) {
obj[i] = initalobj[i];
}
return obj;
}
/* ================ 客户端调用 ================ */
var obj = {
a: "hello",
b: {
a: "world",
b: 21
},
c: ["bob", "tom", "jenny"],
d: function() {
alert("hello world");
}
}
var cloneobj = simpleclone(obj); // 对象拷贝
console.log(cloneobj.b); // {a: "world", b: 21}
console.log(cloneobj.c); // ["bob", "tom", "jenny"]
console.log(cloneobj.d); // function() { alert("hello world"); }
// 修改拷贝后的对象
cloneobj.b.a = "changed";
cloneobj.c = [1, 2, 3];
cloneobj.d = function() { alert("changed"); };
console.log(obj.b); // {a: "changed", b: 21} // // 原对象所引用的对象被修改了
console.log(obj.c); // ["bob", "tom", "jenny"] // 原对象所引用的对象未被修改
console.log(obj.d); // function() { alert("hello world"); } // 原对象所引用的函数未被修改
1.2 方法二:object.assign()object.assign() 方法可以把任意多个的源对象自身的可枚举属性拷贝给目标对象,然后返回目标对象。但是 object.assign() 进行的是浅拷贝,拷贝的是对象的属性的引用,而不是对象本身。
var obj = { a: {a: "hello", b: 21} };
var initalobj = object.assign({}, obj);
initalobj.a.a = "changed";
console.log(obj.a.a); // "changed"
二. 深拷贝的实现要实现深拷贝有很多办法,有最简单的 json.parse() 方法,也有常用的递归拷贝方法,和es5中的 object.create() 方法。
2.1 方法一:使用 json.parse() 方法要实现深拷贝有很多办法,比如最简单的办法是使用 json.parse():
/* ================ 深拷贝 ================ */
function deepclone(initalobj) {
var obj = {};
try {
obj = json.parse(json.stringify(initalobj));
}
return obj;
}
/* ================ 客户端调用 ================ */
var obj = {
a: {
a: "world",
b: 21
}
}
var cloneobj = deepclone(obj);
cloneobj.a.a = "changed";
console.log(obj.a.a); // "world"
这种方法简单易用。
但是这种方法也有不少坏处,譬如它会抛弃对象的constructor。也就是深拷贝之后,不管这个对象原来的构造函数是什么,在深拷贝之后都会变成object。
这种方法能正确处理的对象只有 number, string, boolean, array, 扁平对象,即那些能够被 json 直接表示的数据结构。regexp对象是无法通过这种方式深拷贝。
2.2 方法二:递归拷贝代码如下:
/* ================ 深拷贝 ================ */
function deepclone(initalobj, finalobj) {
var obj = finalobj || {};
for (var i in initalobj) {
if (typeof initalobj[i] === 'object') {
obj[i] = (initalobj[i].constructor === array) ? [] : {};
arguments.callee(initalobj[i], obj[i]);
} else {
obj[i] = initalobj[i];
}
}
return obj;
}
上述代码确实可以实现深拷贝。但是当遇到两个互相引用的对象,会出现死循环的情况。
为了避免相互引用的对象导致死循环的情况,则应该在遍历的时候判断是否相互引用对象,如果是则退出循环。
改进版代码如下:
/* ================ 深拷贝 ================ */
function deepclone(initalobj, finalobj) {
var obj = finalobj || {};
for (var i in initalobj) {
var prop = initalobj[i];
// 避免相互引用对象导致死循环,如initalobj.a = initalobj的情况
if(prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === array) ? [] : {};
arguments.callee(prop, obj[i]);
} else {
obj[i] = prop;
}
}
return obj;
}
2.3 方法三:使用object.create()方法直接使用var newobj = object.create(oldobj),可以达到深拷贝的效果。
/* ================ 深拷贝 ================ */
function deepclone(initalobj, finalobj) {
var obj = finalobj || {};
for (var i in initalobj) {
var prop = initalobj[i];
// 避免相互引用对象导致死循环,如initalobj.a = initalobj的情况
if(prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === array) ? [] : object.create(prop);
} else {
obj[i] = prop;
}
}
return obj;
}
三. 参考:jquery.extend()方法的实现jquery.js的jquery.extend()也实现了对象的深拷贝。下面将官方代码贴出来,以供参考。
官方链接地址:https://github.com/jquery/jquery/blob/master/src/core.js。
jquery.extend = jquery.fn.extend = function() {
var options, name, src, copy, copyisarray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// 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 ( i === length ) {
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;
};
以上就是javascript 中对象的深拷贝的详细介绍的内容。