日期:2014-05-16 浏览次数:20473 次
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());
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;
}