js深度克隆

function highClone(oldObj){

  var cloneObj;

  if(oldObj.constructor==Object || oldObj.constructor==Array){
    cloneObj=new oldObj.constructor;
  }else{
    cloneObj=new oldObj.constructor(oldObj.valueOf());//个人认为这样没什么用,因为克隆方法用于复制对象,其他实例不适用,此处还不如换成return
  }

  for(var i in oldObj){

    if(typeof oldObj[i]=="object"){
      cloneObj[i]=highClone(oldObj[i]);
    }else{
      cloneObj[i]=oldObj[i];
    }  
  }
  cloneObj.toString=oldObj.toString;
  cloneObj.valueOf=oldObj.valueOf;

  return cloneObj;
}

 

//测试

var testObj={"1":[1,2,3],"2":{"aa":"aa","bb":"bb"},"3":function(){var dd="";}};
var testArr=[[1,2,3],{"aa":"aa","bb":"bb"},function(){var dd="";}];


var arrClone=highClone(testArr);
var ObjClone=highClone(testObj);

 

 

posted @ 2014-04-08 12:45  北异  阅读(489)  评论(0编辑  收藏  举报