One option, arguably the most agile, would be to define clone methods for each class that you need to clone, such as:
class Ship
{
public var prop1:Number;
public var otherClassInstance:OtherClass;
public function clone():Ship
{
var result:Ship = new Ship();
result.prop1 = this.prop1;
result.otherClassInstance = this.otherClassInstance.clone()
}
}
class OtherClass
{
public var prop1:Number;
public function clone():OtherClass
{
var result:OtherClass = new OtherClass();
result.prop1 = this.prop1;
}
}
Another option is to clone an object by using the ByteArray class like this example from the Adobe documentation:
function clone( source:Object ):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject( source );
myBA.position = 0;
return( myBA.readObject() );
}
I've seen instances where this approach does not work for cloning instances of custom classes, specifically view classes like Sprites.
Another approach is to use describeType
from the flash.utils
package. With describeType
you can iterate through the properties of an object.
Here is an example of using describeType
to inspect the properties of an object that is a part of a utils lib I wrote.
As for checking the type of the property, you can use describeType
or you can also use the is
operator like this:
if( myObj is SomeClass )
{
}
if( myObj is OtherClass )
{
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…