Exploiting Actionscript 3’s “this” keyword for fun and profit

I originally posted this as a reply to a topic over at the Flashpunk developer forums and thought it would make a good post all on its own.

Something I really like about as3 is that you can define functions anywhere, even within other functions. Such a function is called a closure, as it “closes over” its surrounding environment and has access to all variables that exist in the current scope. For example, you can do this:

When the alarm triggers (after one second, for those unfamiliar with Flashpunk), the closure is called and the message “Hello, world!” is displayed. The function will keep a reference to the message variable as long as it’s being used, long after the function it was created in goes out of scope.

The trouble begins when you use the this keyword inside a function you’re going to pass as a callback.

You’d expect that this would refer to the object that was in scope at the time the function was created; for example, running this code from your player class should trace “[class Player]”. Unfortunately that’s not the case; this always refers to the object that calls the function. In this case, the callback is being called by the Alarm, so it will trace “[class Alarm]”.

This can actually be helpful at times, such as if you pass a function to a GUI control, like so:

In most cases, however, this behavior is just a pain and causes crashes that can’t be caught at compile-time. There’s a solution to that as well, though:

Since self is captured by the function, it will always refer to the this object at the time of the function’s creation; in this case, the Player class instance. This code will trace out “[class Player]”, just as expected.

The Actionscript family of languages is ultimately based on ECMAScript, so a lot of the quirks present in Javascript carry over. Some of them can be annoying to get used to, but as long as you’re aware of them they can serve you well.