3

sometimes we need clone a object.but if a displayObject has some children and use the function like this:

function clone(source:*):*
{
    var b:ByteArray = new ByteArray();
    b.writeObject(source);
    b.position = 0;
    return(b.readObject());
}

but the result has no children.. .. . so what should I do ?

Marty
  • 39,033
  • 19
  • 93
  • 162
Lee
  • 97
  • 2
  • 13

2 Answers2

3

Unfortunately automatic cloning of objects in actionscript is a waste of time in the majority of cases.

Your snippet is right, but serialization/deserialization via ByteArray cannot perform real deep copy, i.e. copying of all references and containers. ByteArray technique will work only with non-reference data types (Number, int, String, etc.)

So there is no silver bullet and only one adequate solution - to write the clone() method for your class manually.

Dmitry Sapelnikov
  • 1,129
  • 8
  • 16
  • +1, I have tried Lee's clone function, it does copy the object but the new copy didn't have the mx_internal_uid, so comparing the copy object with the original one failed. Looks like I will have to write my own method for the clone as you pointed out. – code90 Feb 29 '12 at 18:39
1

I didn't have to program a clone-method myself yet, but i found a way that might do the trick. By iterating through all your variables (in an xml-representation), you can copy them in a new instance of your class.

you can find the method i am talking about on this link: http://www.learnosity.com/techblog/index.cfm/2008/2/6/AS3--Looping-over-properties-of-a-class

Let me know if it works, i'm kind of curious myself :)

Michiel Standaert
  • 4,096
  • 7
  • 27
  • 49