User Guide

360 Handling Events
trace("the this keyword refers to: " + this);
}
}
When a user interacts with the resulting SWF file by clicking on the red square, Flash Player
generates the following trace output:
clickHandler detected an event of type: click
the this keyword refers to: [object ChildSprite]
Note that the this keyword refers to the ChildSprite instance named child. This is a change
in behavior from ActionScript 2.0. If you used components in ActionScript 2.0, you may
remember that when a class method was passed in to
UIEventDispatcher.addEventListener(), the scope of the method was bound to the
component that broadcast the event instead of the class in which the listener method was
defined. In other words, if you used this technique in ActionScript 2.0, the
this keyword
would refer to the component broadcasting the event instead of the ChildSprite instance.
This was a significant issue for some programmers because it meant that they could not access
other methods and properties of the class containing the listener method. As a workaround,
ActionScript 2.0 programmers could use the
mx.util.Delegate class to change the scope of
the listener method. This is no longer necessary, however, because ActionScript 3.0 creates a
bound method when
addEventListener() is called. As a result, the this keyword refers to
the ChildSprite instance named
child, and the programmer has access to the other methods
and properties of the ChildSprite class.
Event listener that should not be used
There is a third technique in which you create a generic object with a property that points to
a dynamically assigned listener function, but it is not recommended. It is discussed here
because it was commonly used in ActionScript 2.0, but should not be used in ActionScript
3.0. This technique is not recommended because the
this keyword will refer to the global
object instead of your listener object.
The following example is identical to the previous ClickExample class example, except that
the listener function is defined as part of a generic object named
myListenerObj:
package
{
import flash.display.Sprite;
public class ClickExample extends Sprite
{
public function ClickExample()
{
var child:ChildSprite = new ChildSprite();
addChild(child);