1. 程式人生 > >javascript深度拷貝

javascript深度拷貝

object rop turn ssim copy obj cal 拷貝 var


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深度拷貝