views:

141

answers:

2

I have a overriden function in my class, that adds an event handler like so:

override public function hide():void {
  ...
  tween.addEventListener(TweenEvent.MOTION_FINISH, function(evt:Event):void {
    ...
    super.hide();
  }, false, 0, true);
}

This does not work, Flash tells me: "1006: A super expression can be used only inside class instance methods." (it works if moved to a proper instance method).

So I would like to understand why can't I use call to super.hide(); from my in-place handler function?

I can refer to any instance variables and methods from there without problems, so I thought that that handler had access to proper context. Please help me understand this.

+5  A: 

it is, because this in an anonymous function points to [object global] ... have a go, and trace it ...

now an AS3 feature is, that you can access instance members from inside there, but that's a really strange feature ... this.myProp will not work, whereas myProp will ... this is some dark magic, that automatically creates a closure ... for some reason it works with instance members, but not with super ...

IMHO, you should not use anonymous functions anyway, only if it is for prototyping, or as parameters for Array methods as forEach, map, filter and the like ...

back2dos
Sorry for such long break. I traced some stuff like you said, googled more, read more docs and found no direct answer... Your dark magic theory seems best ;) In ASDoc it says in 'super' keyword definition that it may not be used in static context, obviosly, maybe AS treats global as static. Don't know.
kret
+1  A: 

I believe you can capture the method in a variable that gets stored in the anonymous method's closure. For instance:

override public function hide():void {
    ...
    var f:Function=super.hide;
    tween.addEventListener(TweenEvent.MOTION_FINISH, function(evt:Event):void {
        ...
        f();
    }, false, 0, true);
}

I can explain further if you are struggling with the concept of closure.

spender
I guess I should read up on closures to have more than general idea. Thanks :)
kret