views:

1514

answers:

3

This is probably a very simple question, I just don't have the foggiest how to go about it.

I have an Object that I want to duplicate, and don't know how to go about it. Here's my attempt:

var myObj = new ObjectClass();
var duplicate = myObj;
duplicate = null;
myObj.function(); // Error: Null reference

The ObjectClass is very large, inherets and creates children of it's own, and I'm sure there's probably a few singleton classes in there.

Is there a way to duplicate something easily?

Edit: Looks like I'm looking for "Cloning", for which there is no AS3 function, and you apparantly can't clone Private data anyway. Anyone know of a library or a workaround for cloneing a bunch of private data?

+1  A: 

You can use ObjectUtil.copy() (a Flex library). But you are right that it doesn't support private data. So this is a shot in the dark but I wonder if you serialize it to AMF using ByteArray.writeObject() if that will copy the private data? Might be worth trying.

James Ward
I just tried the ByteArray approach and that doesn't seem to work. Sorry.
James Ward
+3  A: 

I got this util function from some blog, can't remember from where so I can't give the credit. It wouldn't work with bitmapdata though. Anyway here it is:

public static function copy(o:Object):Object 
{
 var bytes:ByteArray = new ByteArray( );
 bytes.writeObject( o );
 bytes.position = 0;
 return bytes.readObject( );
}

Usage:
registerClassAlias("com.tests.TestClass", TestClass); var testCopy:TestClass = TestClass(ObjectUtil.copy(test));

Gerald Yeo
Ah yes, this seems to do the trick. Thanks so much!!Appears to be from this blog: http://www.darronschall.com/weblog/2007/08/on-transient-objectutilcopy-and-casting.cfm
Andy Moore
As noted below that works to copy public properties but doesn't work with private properties.
James Ward
The code above is the actual implementation of Flex's ObjectUtil.copy() method, so if you're working in Flex, you can use the ObjectUtil class directly instead of using above code.
Stiggler
Ah yes, very true. It doesn't copy private properties.
Andy Moore
You would need to make a custom clone function for your ObjectClass, which is probably better. Maybe by using the copy util to clone public properties, and then manually cloning the private ones?
Gerald Yeo
A: 

just look at this example http://www.ntaka.co.za/how-to-clone-objects-using-flex

ntaka