微博客

 方案一:利用现代浏览器支持的JSON对象做一次中转,实现深度克隆。(IE6、IE7不支持原生JSON对象,可载入json2.js补丁来达到兼容)感谢rekey提供此方案。JSON.stringify()与JSON.parse()详细信息请点击这里

var deepClone = function (obj) {
    var _tmp,result;
    _tmp = JSON.stringify(obj);
    result = JSON.parse(_tmp);
    return result;
}
var obj1 = {family:{brother:"wangzhipeng",father:"wanglicai",mother:"sunaiyun"},name:"gino",sex:"male",age:"27"};
var obj2 = deepClone(obj1);
obj1.family.brother = "close";
console.log(obj1); 
console.log(obj2); 

 

方案二:确定参数类型为object (这里仅指object literal、Array literal)后,复制源对象的键/值到目标对象,否则直接返回源对象。

注:下面这个函数只能说基本满足生产需求,如果参数是Dom对象、new Object ()的话,就会产生功能性错误,要兼容参数的所有数据类型,请点击这里

var deepClone = function fnDeepClone(obj){
    var result = typeof obj.splice === 'function'?[]:{},
    key;
    if (obj && typeof obj === 'object'){
        for (key in obj ){
            if (obj[key] && typeof obj[key] === 'object'){
                result[key] = fnDeepClone(obj[key]);//如果对象的属性值为object的时候,递归调用deepClone,即再把某个值对象复制一份到新的对象的对应值中
            }else{
                result[key] = obj[key];//如果对象的属性值不为object的时候,直接复制参数对象的每一个键/值到新对象对应的键/值中
            }
            
        }
        return result;
    }
    return obj;
    

}

//test array
var arry1= ["a","b","c","d"];
var arry2 = deepClone(arry1);
arry1.pop();
console.log(arry1);
console.log(arry2);

//test object
var obj1 = {name:"gino",sex:"male",age:27,favorite:"pingpang",family:{brother:"zhipeng",mother:"SunAiyun",father:"WangLicai"}};
var obj2 = deepClone(obj1);
obj1.family.brother = "close";
console.log(obj1);
console.log(obj2);

 

 方案三:利用数组的Array.prototype.forEach和其他一些ECMAScript 5中的Object.*函数。经测试,当值的类型为object的时候,会出现功能错误。个人水平有限,没看懂这个函数,如有朋友能帮忙修正下此函数,万分感激。 链接

var deepClone = function (o){
  var copy = Object.create( Object.getPrototypeOf(o) );
  var propNames = Object.getOwnPropertyNames(o);
 
  propNames.forEach(function(name){    
    var desc = Object.getOwnPropertyDescriptor(o, name);   
    Object.defineProperty(copy, name, desc);        
  });
 
  return copy;
}
 
var obj1 = {family:{brother:"wangzhipeng",father:"wanglicai",mother:"sunaiyun"},name:"gino",sex:"male",age:"27"};
var obj2 = deepClone(obj1);
obj1.sex = "close";
console.log(obj1); 
console.log(obj2); 

 

posted on 2013-04-11 14:16  飞鸟42  阅读(10664)  评论(1编辑  收藏  举报