Skip to main content
Inspiring
February 14, 2013
Question

Dynamically create variable type using string value

  • February 14, 2013
  • 1 reply
  • 1652 views

Hi. In my project I created several classes named Square1, Square2, Circle 1, Circle2, Triangle1, Triangle2, etc. They all extend MovieClip and the create different shapes and have slightly different properties that set them appart.

There comes a point when I need to instance them and add the instances to the stage. I do this through buttons that have a sType:String property, that corresponds to the name of the class they should instantiate. So button S1 has sType = "Square1", and so on.

Now, what I would like to do is, instead of having a ton of handler functions for all the buttons, have only a single function that handles all the buttons and decides which class to instantiate. It would be something like this:

function buttonClicked ($event:MouseEvent):void {

     var instanceClass:String = $event.target.sType; //let's say it's "Square1"

     var newShape:MovieClip = new [instanceClass]();

}

Is this possible?

Thank you.

This topic has been closed for replies.

1 reply

kglad
Community Expert
Community Expert
February 14, 2013

use:

function buttonClicked ($event:MouseEvent):void {

var C:Class=Class(getDefinitionByName($event.currentTarget.sType));

var instance:*=new C();

addChild(instance);

}

Inspiring
February 14, 2013

Thank you.

However, when I used getDefinitionByName I get "error #1065 variable is not defined". I also tried something I saw in another forum:

var C:Class = getDefinitionByName($event.currentTarget.sType) as Class;

but I got the same error. Reading my initial post I see I forgot to mention that Square1, etc. are linked to library items, but I don't think this makes a difference. I tried changing sType to a class that is not linked and I got the error again.

kglad
Community Expert
Community Expert
February 15, 2013

use:

trace($event.currentTarget.sType) to see which sType variable is not defined.

p.s. you did mean to say you were using movieclips, not buttons??  ie, S1 is not a simple button but a movieclip button, correct?