user427969
user427969

Reputation: 3896

AS3 - Clone class object when class has parameterized constructor

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

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;
        }
    }
}

BUT this only works when the class has a default constructor and not when it has parameterized constructor:

Any idea on how to clone a class object when the class has a parameterized constructor?

Regards

Upvotes: 1

Views: 1282

Answers (3)

Justin Ohms
Justin Ohms

Reputation: 3523

My suggestion would be to not make it too complicated and not over think things. There really is no need to do anything more complicated than this.

 public function clone():Thing {
     var t:Thing = new Thing();

     t.x = this.x;
     t.y = this.y;
     t.val1 = this.val1;
     t.val2 = this.val2;

     return t;
 }

and if you have a parameters in your constructor.

public function Thing(x:int,y:int) {
    this.x = x;
    this.y = y;
}

public function clone():Thing {
    var t:Thing = new Thing(this.x, this.y);

    t.val1 = this.val1;
    t.val2 = this.val2;

    return t;
}

I do like the other answer, it's clever but a lot of churn for just setting some properties. Don't over think the problem.

Upvotes: 0

Rytis Alekna
Rytis Alekna

Reputation: 1377

You can create a class with constructor that has optional parameters. This is a good practice from test driven development and performance point.

Upvotes: 0

Marty
Marty

Reputation: 39456

This is the best I could do for you:

package
{

    import flash.display.Sprite;


    public class Thing extends Sprite
    {

        // Cloneable properties.
        private var _cloneable:Array = ["x","y","val1","val2"];


        // Properties.
        public var val1:uint = 10;
        public var val2:String = "ten";


        /**
         * Returns a new Thing with the same properties.
         */
        public function clone():Thing
        {
            var t:Thing = new Thing();

            for each(var i:String in _cloneable)
            {
                t[i] = this[i];
            }

            return t;
        }

    }

}

All you need to do is add the properties you want to have clone-able to _cloneable

Example use:

var thing:Thing = new Thing();

thing.x = 15;
thing.y = 10;
thing.val1 = 25;
thing.val2 = "twentyfive";

// Clone initial Thing.
var thing2:Thing = thing.clone();

trace(thing2.x, thing2.y, thing2.val1, thing2.val2); // 15 10 25 twentyfive

Upvotes: 2

Related Questions