What is the best method to deep clone objects in actionscript?
Asked
Active
Viewed 1,345 times
2 Answers
10
The best method to do this is by using the ByteArray with the method writeObject. Like this:
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
More information about this, here: http://www.kirupa.com/forum/showpost.php?p=1897368&postcount;=77

rzetterberg
- 10,146
- 4
- 44
- 54
-
1I'm not sure if that deep clones something. I remember testing something like this ages ago. It works, but if you have something like a Vector of objects, then you'll end up with a new Vector with the same objects in it in the clone – divillysausages Apr 27 '11 at 08:05
-
If you can show me how this not works or another solution which works better, then it is much welcomed :) – rzetterberg Apr 27 '11 at 08:07
-
2Ok, I just tested it here and it works, ignore my previous comment. You'll need to use `registerClassAlias()` on your class if you want to retain type safety though. Both on the class itself and on any classes inside it. E.g. if you have a class `TestClass` that holds a `Vector` of `Sprites`, you'll need to call `registerClassAlias()` on `TestClass` as well as `Sprite` otherwise you'll return an `Object` with `Vector` of `Objects` that have all the properties of `Sprites` – divillysausages Apr 27 '11 at 08:34
-
You can do this in the `clone()` for the object itself by calling `getQualifiedClassName()` on the object to get the classname, then `getDefinitionByName( className ) as Class` to get the class. For any internal class, you could create an interface `IClonable` or something that returns a list of classnames with classes. Then in your `clone()` function, you can see is it an `IClonable`, then call `registerClassAlias()` on it's list – divillysausages Apr 27 '11 at 08:41
0
If you are trying to deep clone a display object, this is the only way it worked for me :
public static function clone(target:DisplayObject ):DisplayObject {
var bitmapClone:Bitmap = null;
var bitmapData:BitmapData = new BitmapData(target.width,target.height,true,0x00000000);
bitmapData.draw(target);
bitmapClone = new Bitmap(bitmapData);
bitmapClone.smoothing = true;
return bitmapClone;
}
Note that this will only copy visually the object.It will not copy methods or properties. I used this when i loaded external images, and used them in multiple places.

Mihai Raulea
- 428
- 1
- 3
- 18