js深拷贝和浅拷贝【2015-05-19】

维基百科对深浅拷贝的解释:

浅拷贝:

One method of copying an object is the shallow copy. In the process of shallow copying A, B will copy all of A’s field values. If the field value is a memory address it copies the memory address, and if the field value is a primitive type it copies the value of the primitive type.

浅拷贝的缺点是如果你改变了被拷贝对象所指向的内存地址,你同时也改变了拷贝对象的地址的字段。

js中的赋值都为引用传递,就是说,在把一个对象赋值给一个变量时,这个变量所指向的仍旧是原来对象的地址,引用就是浅拷贝。

深拷贝:

An alternative is a deep copy. Here the data is actually copied over. The result is different from the result a shallow copy gives. The advantage is that A and B do not depend on each other but at the cost of a slower and more expensive copy.

深拷贝就是不仅复制对象的基本类,同时也复制对象中的对象,就是说对象完全是新对象产生的,新对象所指向的不是原来对象的地址。

//浅拷贝

1
2
3
4
5
6
7
8
9
function shallowCopy(oldObj){
var newObj={};
for(var i in oldObj){
if(oldObj.hasOwnProperty(i)){
newObj[i]=oldObj[i];
}
}
return newObj;
}

 

//深拷贝

1
2
3
4
5
6
7
8
9
function deepCopy(oldObj){
var newObj=oldObj;
if(oldObj && typeof oldObj === 'object'){
newObj=Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
for(var i in oldObj){
newObj[i]=deepCopy(oldObj[i]);
}
}
}
posted @ 2015-07-22 12:20  憔悴心只为你  阅读(265)  评论(0编辑  收藏  举报