views:

1444

answers:

1

Hi, I'm simply playing around with basic ActionScript 3 using Flash CS3 Pro.

I put in a keyframe this very simple code to duplicate n "brander" symbols:

for (var i:Number=0; i<20; i++) {
    var m = new brander("MS_"+i);
    addChild(m);
    m.name = "MS_"+i;
    m.x = 20*i;
    m.alpha = a;
    a-=0.05;
    m.y = 20;
}

The symbol is linked to brander.as class.

The class is this one:

package {
    import flash.display.*;
    public class brander extends MovieClip {
     var n:String;
     //
     public function brander(name) {
      setName(name);
     }
     //
     function setName(name) {
      this.n = name;
     }
     //
     function getName() {
      return n;
     }
    }
}

and it is simple too.

Now: I noticed I can't really set anything in this class. So, when I call setName (at the creation of a "brander" instance), I don't set anything. Is this possible?

I tested without debugging, by simply writing:

btn.addEventListener(MouseEvent.MOUSE_DOWN, test);
//
function test(EVT) {
    trace(this.getChildByName("MS_2").getName());
}

Why do we link a class when this class can't store information? What am I doing wrong?


EDIT:

I found this is working:

function fun(EVT) {
    trace((this.getChildByName("M_2") as brander).getName());
}

but I can't understand WHY: could you please tell me why?

+1  A: 

The reason is that the getChildByName() funcction returns a DisplayObject. The DisplayObject has no getName function. The brander class however inherits from (extends) the DisplayObject, and therefore you can store it as a DisplayObject. But if you want to call any of the brander functions, you need to cast it to brander first, using as.

There is lots of information on casting, polymorphism and inheritance several places on the internet.

Marius
I know what casting, etc. actually are in terms of OOP. As a seasoned AS1 and AS2 developer (slowly and lazily moving to AS3) I thought it was some Flash authoring issue, not a programming-related one. Thanks you for taking the time to reply.