views:

53

answers:

2

i have many objects of the same custom class, and another many objects of another custom class. i would like to create a switch statement to determine from which of the classes the object belongs. the following code doesn't compile, so i'm not sure if this is possible. is the only alternative to use if statements?

function mouseClickEventHandler(evt:MouseEvent):void
     {
     switch (evt.currentTarget)
            {
            case (is customClassA):  trace("is instance of customClassA");  break
            case (is customClassB):  trace("is instance of customClassB");
            }
     }
+11  A: 

This should work:

function mouseClickEventHandler ( evt:MouseEvent ):void
{
    switch ( evt.currentTarget.constructor )
    {
        case CustomClassA:
            trace("is instance of customClassA");
            break;

        case CustomClassB:
            trace("is instance of customClassB");
            break;
    }
}

See Object.constructor.

poke
rad. totally didn't know about this. thanks!
TheDarkInI1978
+1. Cool. I didn't know this was possible.
Juan Pablo Califano
+1  A: 
function clickHandler (event:MouseEvent):void
{
    var target:Object = event.currentTarget;
    switch (true)
    {
        case (target is CustomClassA):
            trace("is instance of customClassA");
            break;

        case (target is CustomClassB):
            trace("is instance of customClassB");
            break;
    }
}

Not sure if braces are needed

Pavel fljōt