开发者

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 anotherS开发者_运维问答prite:Sprite = makeAnotherSprite(mySprite);

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


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


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


Make that:

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

(Brackets)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜