Using the Delegate class 347
Scope of the this keyword
The this keyword refers to the object in the currently executing scope. Depending on what
type of event handler technique you use,
this can refer to different objects.
Within an event handler or event listener function, this refers to the object that defines the
event handler or event listener method. For example, in the following code,
this refers to
my_mc:
// onPress() event handler attached to main timeline:
my_mc.onPress = function () {
trace(this); // _level0.my_mc
}
Within an on() handler attached to a movie clip
, this refers to the movie clip to which the
on() handler is attached, as shown in the following code:
// Attached to movie clip named my_mc on main timeline
on (press) {
trace(this); // _level0.my_mc
}
Within an on() handler attached to a button
, this refers to the timeline that contains the
button, as shown in the following code:
// Attached to button on main timeline
on (press) {
trace(this); // _level0
}
Using the Delegate class
The Delegate class lets you run a function in a specific scope. This class is provided so that
you can dispatch the same event to two different functions (see “Delegating events to
functions” in Using Components), and so that you can call functions within the scope of the
containing class.
When you pass a function as a parameter to
EventDispatcher.addEventListener(), the
function is invoked in the scope of the broadcaster component instance, not the object in
which it is declared (see “Delegating the scope of a function” in Using Components). You can
use
Delegate.create() to call the function within the scope of the declaring object.
The following example shows three methods of listening for events for a Button component
instance. Each way that you add event listeners to a Button component instance results in the
event being dispatched in a different scope.