JavaScript clone object

Since I did not easily find a good all browser, all kinds of object cloning funtion on the net, here's my one

function cloneObject (obj)
{
  if ( !obj )
  {
    return null;
  }

  // check for function, RegExp, and Date objects, and non-object types
  if ( typeof obj != 'object' || obj instanceof Function || obj instanceof RegExp || obj instanceof Date)
  {
    newObj = obj; // just copy reference to it
  }
  else
  {
    var newObj = (obj instanceof Array) ? [] : {};
    for ( var n in obj )
    {
      var node = obj[n];
      if ( typeof node == 'object' )
      {
        newObj[n] = cloneObject(node);
      }
      else
      {
        newObj[n] = node;
      }
    }
  }

  return newObj;
};

var x = {a: 1, b : "OK", c : /test$/, d: [1,2], e : {a:'OK'}, f: function(arg){alert(arg)}};
var y = cloneObject(x);

alert(typeof y.a +': '+y.a);
alert(typeof y.b +': '+y.b);
alert('RegExp: ' +'true: '+y.c.test("test") + ' false: '+y.c.test("testx"));
alert('Array: ' + y.d.join(' joinedWith '));
alert('Object: ' + y.e.a);

y.f('Function: OK');

function myClass(a, b)
{
  this.prop = 'Custom Class method call: OK';
}

myClass.prototype.func = function()
{
  alert(this.prop)
}

var t = new myClass();
tClone = cloneObject(t);

tClone.func();
alert('instanceof myClass: ' + (tClone instanceof myClass)); //unfortunately this does not work 


Tags für diesen Artikel:
-->

About this entry