散分,问题仅供讨论
js对象的完美克隆。
先贴一个:Object.prototype.clone=function(){
var myNewObj;
if(this.constructor==Array)
{
myNewObj=this.clone();//是数组的话先按数组的方式克隆其数组部分
}
else
myNewObj=new Object();
for(var i in this)//不管是不是数组,都要将其成员添加到新对象,以确保不丢失在数组上直接扩展的成员
{
if(typeof i!='object') myNewObj[i]=this[i];
else myNewObj[i] = this[i].clone();
}
return myNewObj;
}
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')
itemi= itemi.clone();//是对象就调用方法克隆,如果进一步是数组会自动调用数组的clone方法
newArr.push(itemi);
}
return newArr;
}
js对象的完美克隆。
先贴一个:Object.prototype.clone=function(){
var myNewObj;
if(this.constructor==Array)
{
myNewObj=this.clone();//是数组的话先按数组的方式克隆其数组部分
}
else
myNewObj=new Object();
for(var i in this)//不管是不是数组,都要将其成员添加到新对象,以确保不丢失在数组上直接扩展的成员
{
if(typeof i!='object') myNewObj[i]=this[i];
else myNewObj[i] = this[i].clone();
}
return myNewObj;
}
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')
itemi= itemi.clone();//是对象就调用方法克隆,如果进一步是数组会自动调用数组的clone方法
newArr.push(itemi);
}
return newArr;
}
试着从构造函数去clone。比如:Object.prototype.clone=function(){
var f=function(){};
f.prototype=this.constructor.prototype;
var o=new f();
for(var p in this)if(this.hasOwnProperty(p)){
if(this[p]!=null && typeof this[p].clone=='function')o[p]=this[p].clone();
else o[p]=this[p];
}
try{return o}catch(ex){}finally{f=o=null}
};
Date.prototype.clone=function(){
return new Date(this.getTime())
};
//……还有很多要考虑的东西,赞一个。
var a={'什么东西都行','value'};
var b=a;
这个不就是克隆了吗?
还有其他的这个做不到吗?
在a改变之前这个应该能用吧,不会复制后啊内容改变,b也变吧
求解
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;
}经测试对函数及在函数上进行成员附加都可以正确克隆。调用时都不要传参数,object的方法里参数只是被其他克隆方法调用时使用。
不了解正则,没有写其克隆方法,知道的希望补充一下RegExp对象的克隆
缺陷是必然的,只能尽量完善。没有提供对dom对象的克隆方法,完美确实太难......