In object oriented programming it’s crucial to understand references to objects.

1
2
var obj1 : MyClass = new MyClass();
var obj2 = obj1;

Essentially, this means that obj1 and obj2 are two different objects but pointing to the same reference
So, if you change any properties on obj1 you perform that same changes to obj2.

So what if you wish to clone an object, making them point to different references and be totally independent of each other?
In Java you have the clone method. You don’t have that in ActionScript 3. But there’s a way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package{
    import flash.net.registerClassAlias;
    import flash.utils.ByteArray;

    public class MyClass{
        public var property1        : String;
        public var property2        : Array;

        public function clone() : MyClass{
            registerClassAlias( "MyClass", MyClass );
            var bytes : ByteArray = new ByteArray();
            bytes.writeObject( this );
            bytes.position = 0;
            return bytes.readObject() as MyClass;
        }
    }
}

The above example creates a deep clone of an object and returns that object as a Class of where you can create a new instance with the cloned properties. Many would claim that this method is a hack and I agree. But since true deep cloning is not available in ActionScript 3, this is the way to go.



One Response to “Cloning objects in ActionScript 3”

  1. [...] I want to clone a class object. I tried following from here: [...]

Leave a Reply

You must be logged in to post a comment.



workline