Chunky Chunk
Chunky Chunk

Reputation: 17217

ActionScript - Instantiate New Object From Instance?

how can i instantiate another class object from a class instance?

in the code below (which doesn't work) i'd like the function to return a new class instance based the passed argument's class. in other words, i want the function to return a new instance of MySprite without having to call new MySprite();.

var mySprite:Sprite = new MySprite();
var anotherSprite:Sprite = makeAnotherSprite(mySprite);

function makeAnotherSprite(instance:Sprite):Sprite
    {
    return new getDefinitionByName(getQualifiedClassName(instance));
    }

Upvotes: 1

Views: 1079

Answers (3)

Manish
Manish

Reputation: 3522

Make that:

return new (getDefinitionByName(getQualifiedClassName(instance)))();

(Brackets)

Upvotes: 0

Sam
Sam

Reputation: 1243

An alternative way than what you're trying to do, but should work.

function makeAnotherSprite(instance:Sprite):Sprite
{
var myClass:Class = Object(instance).constructor; 
return new myClass();
}

Upvotes: 1

Gerhard Schlager
Gerhard Schlager

Reputation: 3145

Your solution did almost work. Here's the corrected function:

function makeAnotherSprite(instance:Sprite):Sprite
{
    var qualifiedClassName:String = getQualifiedClassName(instance);
    var clazz:Class = getDefinitionByName(qualifiedClassName) as Class; 
    return new clazz();
}

Upvotes: 3

Related Questions