javascript设计模式交流
2010-09-14 13:17:22 来源:WEB开发网String Boolean Number都是只读的对象,所以只要=就可以了。
完美的clone
为了实现完整的clone三种类型,要把上面的方法结合起来。
/************************************/
function clone()
{
var ret;
if(this instanceof Function)
{
ret=Function(new String("return ")+this)();
}
else if(this instanceof Array)
{
ret=new Array();
}
else if(this instanceof Date)
{
ret=new Date();
ret.setTime(this.getTime());
}
else if( (this instanceof String) || (this instanceof Boolean) || (this instanceof Number) )
{
return this;
}
else ret=new Object(); for(var p in this)
{
ret[p]=this[p];
}
return ret;
}
function deepClone()
{
var ret;
if(this instanceof Function)
{
ret=Function(new String("return ")+this)();
}
else if(this instanceof Array)
{
ret=new Array();
}
else if(this instanceof Date)
{
ret=new Date();
ret.setTime(this.getTime());
}
else if( (this instanceof String) || (this instanceof Boolean) || (this instanceof Number) )
{
return this;
}
else ret=new Object();
for(var p in this)
{
if(typeof ret[p]!="object")ret[p]=this[p];
else ret[p]=deepClone.call(this[p]);
}
return ret;
}
function prototypeClone()
{
if(this instanceof Function)
{
var tmp=Function.prototype;
Function.prototype=this;
var ret=(new Function(new String("return ")+this))();
Function.prototype=tmp;
return ret;
}
else if(this instanceof Array)
{
var tmp=Array.prototype;
Array.prototype=this;
var ret=new Array();
Array.prototype=tmp;
return ret;
}
else if(this instanceof Date)
{
var tmp=Date.prototype;
Date.prototype=this;
var ret=new Date();
ret.setTime(this.getTime());
Date.prototype=tmp;
return ret;
}
else if( (this instanceof String) || (this instanceof Boolean) || (this instanceof Number) )
{
return this;
}
else
{
var constructor=function(){};
constructor.prototype=this;
return new constructor;
}
}
Tags:javascript 设计模式 交流
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接