Wednesday, September 10, 2008

Javascript cloning object

Cloning Objects in Javascript

This example illustrates how to clone an object in javascript. It would allow to call clone() on any object to make a copy of the respective object.










Object.prototype.clone = function () { // prototype for clone method in object
function c(o) {
for (var i in o) {
this[i] = o[i];
}
}
return new c(this);
};

var t = new Object();
t.test = "xyz";
t.setTest = function(a) {
this.test = a;
}

t.getTest = function () {
return this.test;
}

alert(t.getTest());
var u = t.clone(); // cloning of object
u.setTest("abc");
alert(u.getTest());
alert(t.getTest());