1

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

3 Answers 3

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

nice! i forgot all about using the constructor property. this is much cleaner than having to use the flash.utils static functions. thanks!
0

Make that:

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

(Brackets)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.