首页 > 代码库 > javascript深度拷贝

javascript深度拷贝


Object.prototype.deepCopy=function(){
var obj=arguments[0]||{};
for(var i in this){
if(this.hasOwnProperty(i)){
if(isSimpleObject(this[i])){
obj[i]={};
this[i].deepCopy(obj[i]);
}else if(isArray(this[i])){
obj[i]=[];
this[i].deepCopy(obj[i]);
} else {
obj[i]=this[i];
}
}
}
return obj;
}

var isSimpleObject=function (obj) {
return Object.prototype.toString.call(obj)===‘[object Object]‘;
}

var isArray=function (arr) {
return Object.prototype.toString.call(obj)===‘[object Array]‘;
}

var obj={x:1,y:[1,2,3],z:{x:1},n:function(){return this.x}}

var obj1=obj.deepCopy();

javascript深度拷贝