Entry
How do I clone an Object?
How do I clone an Array?
How to clone the object if between it and its properties there is a relations like parent-child
May 25th, 2006 05:16
chris burgess, Martin Honnen, Mikayel Aghasyan, http://kb.mozillazine.org/Differential_inheritance_in_JavaScript
The following adds a method
clone
to the prototype of
Object
The method has one optional boolean argument
deep
which when set recursively creates a deep copy, otherwise (when deep is
false or not defined) a shallow copy is created.
function clone (deep) {
var objectClone = new this.constructor();
for (var property in this)
if (!deep)
objectClone[property] = this[property];
else if (typeof this[property] == 'object')
objectClone[property] = this[property].clone(deep);
else
objectClone[property] = this[property];
return objectClone;
}
Object.prototype.clone = clone;
//Examples of its use:
function AClass (aField) {
this.aField = aField;
}
AClass.prototype.aMethod = function () { alert(this.aField); };
var anObject = new AClass('Kibology');
var aClone = anObject.clone();
aClone.aMethod();
// cloning of Array:
var anArray = new Array (0, 1, 2);
var arrayClone = anArray.clone();
alert(arrayClone == anArray);
// deep clone compared to shallow clone
var someObject = {aProperty: anArray };
var someObjectClone = someObject.clone();
alert(someObjectClone.aProperty == someObject.aProperty);
var someObjectClone = someObject.clone(true);
alert(someObjectClone.aProperty == someObject.aProperty);
---
Be aware that any function iterating through the properties of your
objects - ALL objects, not just cloned ones - will see the clone
function. By default the Object() prototype has no builtin functions
(that are visible to an iterator), but this one will be.
See the bottom of this page for a workaround:
http://kb.mozillazine.org/Differential_inheritance_in_JavaScript