Another weird trick that I’ve found to come in handy at times is exploiting how as3 resolves this when executing a function object.
function end():void
{
// get the class type of this
trace(Object(this).constructor);
}
var alarm:Alarm = new Alarm(1, end);
You’d expect that this would refer to the current object; for example, running this code 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:
function click():void
{
var self:Button = this as Button;
// from now on, self refers to the button that's being clicked
// this code will also compile with no problems
// while it wouldn't without the proxy object and cast
}
button.onClick = click;
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:
var self:Player = this;
function end():void
{
trace(Object(self).constructor);
}
var alarm:Alarm = new Alarm(1, end);
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.
Edit: Should I maybe turn this into a tutorial? I remember having all kinds of trouble with this kind of thing when I was first starting out.