Javascript对象深拷贝

来源:互联网 发布:百战天下强化数据 编辑:程序博客网 时间:2024/05/16 05:00
Object.prototype.clone = function()
{
 if(typeof(this) != "object")
 {
  return this;
 }
 
 var cloneDepth = ((arguments.length >= 1)?((isNaN(parseInt(arguments[0])))?(null):parseInt(arguments[0])):null);
 if (cloneDepth)
 {
  cloneDepth=((cloneDepth <= 0)?(null):(cloneDepth));
 }
 var cloneObject = null;
 var thisConstructor = this.constructor;
 var thisConstructorPrototype = thisConstructor.prototype;
 if (thisConstructor == Array)
 {
  cloneObject = new Array();
 }
 else
 if(thisConstructor == Object)
 {
  cloneObject = new Object();
 }
 else
 {
  try
  {
   cloneObject = new thisConstructor;
  }
  catch(exception)
  {
   cloneObject = new Object();
   cloneObject.constructor = thisConstructor;
   cloneObject.prototype = thisConstructorPrototype;
  }
 }
 
 var propertyName = "";
 var newObject=null;
 for (propertyName in this)
 {
  newObject = this[propertyName];
  if (!thisConstructorPrototype[propertyName])
  {
   if (typeof(newObject)=="object")
   {
    if (newObject === null)
    {
     cloneObject[propertyName] = null;
    }
    else
    {
     if(cloneDepth)
     {
      if(cloneDepth == 1)
      {
       cloneObject[propertyName] = null;
      }
      else
      {
       cloneObject[propertyName] = newObject.clone(--cloneDepth);
      }
     }
     else
     {
      cloneObject[propertyName] = newObject.clone();
     }
    }
   }
   else
   {
    cloneObject[propertyName] = newObject;
   }
  }
 }
 
 return cloneObject;
};