Maybe I'm not quite getting the concept, but a "copy constructor" should
be a constructor that copies data from another object to the object
being created, right? And (I think) the original poster wanted to know
how to overload constructors in ActionScript so as to have a default
(argument-less) constructor and a copy constructor.

But you can't overload functions in ActionScript. You only get one form
for each method/constructor. But you can make the argument(s) optional,
which is what I did in my example, posted earlier.

In AS3.0, I think the constructor might look more like this:

// ...
function ClassName(source:* = null) {
        super();
        // ...
        if (source is ClassName) {
                copy(ClassName(source))
        } else {
                // Default initialization.
        }
}
public function copy(source:ClassName):void {
        // Copy data from source to this object.
}
/...

Example of code using this class:

var a:ClassName = new ClassName(); // Default initialization.
// Code that modifies a.
var b:ClassName = new ClassName(a); // Creates a copy of a.

Another possibility is to create a clone() method:

// ...
public function clone():ClassName {
        var cloneObj:ClassName = new ClassName();
        cloneObj.copy(this);
        return cloneObj;
}
// ...

―
Mike Keesey

> -----Original Message-----
> From: [EMAIL PROTECTED] [mailto:flashcoders-
> [EMAIL PROTECTED] On Behalf Of Steven Sacks | BLITZ
> Sent: Thursday, November 02, 2006 2:53 PM
> To: Flashcoders mailing list
> Subject: RE: [Flashcoders] Copy Constructor
> 
> How about this?
> 
> class Test {
>       var foo:String;
>       var bar:String;
>       function Test(initObj:Object) {
>               for (var a:String in initObj) {
>                       this[a] = initObj[a];
>               }
>       }
>       public function get data():Object {
>               var obj:Object = {};
>               obj.foo = foo;
>               obj.bar = bar;
>               return obj;
>       }
>       public function copyConstructor():Test {
>               return new Test(data);
>       }
> }
> 
> 
> 
> //
> 
> import Test;
> test1 = new Test();
> test1.foo = "Hello";
> test1.bar = "World";
> test2 = test1.copyConstructor();
> trace(test2.foo);
> trace(test2.bar);
> -- Hello
> -- World
> _______________________________________________
> [email protected]
> To change your subscription options or search the archive:
> http://chattyfig.figleaf.com/mailman/listinfo/flashcoders
> 
> Brought to you by Fig Leaf Software
> Premier Authorized Adobe Consulting and Training
> http://www.figleaf.com
> http://training.figleaf.com

_______________________________________________
[email protected]
To change your subscription options or search the archive:
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders

Brought to you by Fig Leaf Software
Premier Authorized Adobe Consulting and Training
http://www.figleaf.com
http://training.figleaf.com

Reply via email to