读书人

关于复制对象!该怎么解决

发布时间: 2012-09-19 13:43:53 作者: rapoo

关于复制对象!

JScript code
var arr={            name:'cheng',            age:22        };Object.prototype.copy=function(){    var result=new Object();    function iterator(o,result){        for(name in o){            if(!(o[name] instanceof Object)){                result[name]=o[name];                        }else{                arguments.callee(o[name],result[name]);            }                     }        return result;    }    iterator(this,result);    };console.log(arr.copy());



为什么会报错Maximum call stack size exceeded

[解决办法]
问题在于这么种写法,
因为你扩展了Object的prototype,arr实际在for(var name in o)时候会有三个,而不是你期望的name和age,还有一个copy。因为你扩展的copy是属于可 enumerable的。 后面function 也会是Object的instance,所以会进入else statement,完了就一直这样下去了,所以会size exceeded
[解决办法]
对象克隆嘛
JScript code
Object.prototype.clone=function(obj){    var newObj=obj?obj:new Object();    for(var i in this)    {      var objType=typeof this[i];      if(objType=='object' || (objType=='function' && this[i]!=this.clone))//clone这个函数不能进行克隆,否则会陷入无限递归      {        newObj[i] = this[i].clone();      }       else {        newObj[i]=this[i];      }    }    return newObj;}  Array.prototype.clone=function(){    var newArr=new Array();    for(var i=0;i<=this.length-1;i++)    {       var itemi=this[i];       if(typeof itemi=='object' || (typeof itemi=="function" && itemi!=this.clone))          itemi= itemi.clone();//用递归克隆多级数组,根据对象类型自然会调用对应方法;       newArr.push(itemi);    }    Object.prototype.clone.call(this,newArr);//按类型克隆对象后调用Object的clone方法克隆扩展成员;    return newArr;  }  Date.prototype.clone=function(){    var newDate=new Date(this.getTime());    Object.prototype.clone.call(this,newDate);    return newDate;  }  Function.prototype.clone=function(){    eval("var newFun="+this.toString());//使用函数的代码字符串生成新函数对象    Object.prototype.clone.call(this,newFun);    return newFun;  } 

读书人网 >JavaScript

热点推荐