0

I have a MovieClip with an anonymous Touch Event function, and when I execute this.gotoAndStop(2) I get an error that says gotoAndStop() is not a function. However, in a non-anonymous function, I don't get this error.

Any reason why?

Cilan
  • 10,658
  • 3
  • 31
  • 51

1 Answers1

1

Most likely this is not what you expect it to be.

One way around this is this: capture "this" into local variable and use it in function.

....
var me = this;
whatever.addEventListener("foo", function(v:TypeOfEvent)
{ 
   // note that this != me here 
   me.gotoAndStop();
}

If you do the same for member function ActionScript will automatically capture "this" and it will be "bound" properly as descripted in ActionScript:Functions and Bound methods articles:

Methods behave similarly in that they also retain information about the lexical environment in which they were created. This characteristic is most noticeable when a method is extracted from its instance, which creates a bound method. The main difference between a function closure and a bound method is that the value of the this keyword in a bound method always refers to the instance to which it was originally attached, whereas in a function closure the value of the this keyword can change.

So following code will have expected value of this inside member function memeberFunction:

whatever.addEventListener("foo", memberFunction);

Note: ActionScript have very similar rules to JavaScript about this in anonymous functions, so you may find How does the "this" keyword work? question useful.

Community
  • 1
  • 1
Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159