"Thomas Mlynarczyk" <bl*************@hotmail.com> writes:
If A is an object, then "B = A;" will just assign a reference. Isn't there a
simple way to create an actual copy of A and assign that to B?
No, not in general.
There are several ways to do something that resembles it, though, and
depending on the objects' nature and how you intend to use the copy,
you can pick the one that suits you best.
If it is a plain object, you can find all the properties you have added
using enumeration, and assign them to another object:
function copyByEnum(object) {
var copyObject = new Object();
for(var property in object) {
copyObject[property] = object[property];
}
return copyObject;
}
This will not work if the object is not a plain object, but, e.g., a
function or array. It will only copy enumerable properties. On an
Object (something created by the user using only "new Object()" and
inheritance), the only non-enumerable properties are the ones in
Object.prototype. The new copy will also have these because it is
created with "new Object()".
If you want to clone an Array, you can first try to detect that it
is an Array, and then use "copy = new Array(object.length)" instead
of "copy = new Object()". Detection isn't that easy, and it won't
help you for functions.
If you don't want to copy all the properties manually, you can use
prototype-based inheritance. In a prototype based language like
Javascript, inheritance happens directly between objects, and not
through classes as in, e.g., Java. The object you inherit from
is called the "prototype", and when you look up properties,
the ones not found in the new object itself are then searched for
in its prototype. Assignments will write to the new object directly.
function copyByInheritance(object) {
function dummyConstructor(){};
dummyConstructor.prototype = object;
return new dummyConstructor();
}
Again, it won't work for host objects like Arrays and Functions.
These copy methods have been shallow copies. If one of the properties
of the object is itself an object, only its reference is copied. If
you want a deep copy, you will need to look at each property and
determine whether it is an object that should be deep-copied again.
All in all, you need a good reason before you start doing any of
this :)
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'