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: javascript
About this entry
You’re currently reading “JavaScript clone object,” an entry on Raimund Meyer's personal blog
- Geschrieben von:
- Raimund Meyer um
12.08.2009 / 11:38
Last updated 06.09.2010





Noch keine Kommentare
Jump to comment form | Kommentare RSS | Trackback für spezifische URI dieses Eintrags