User Guide

122 Object-Oriented Programming in ActionScript
The following code defines a class named ThisTest, which contains a method named foo()
that defines the bound method, and a method named
bar() that returns the bound method.
Code external to the class creates an instance of the ThisTest class, calls the
bar() method,
and stores the return value in a variable named
myFunc.
class ThisTest
{
private var num:Number = 3;
function foo():void // bound method defined
{
trace("foo's this: " + this);
trace("num: " + num);
}
function bar():Function
{
return foo; // bound method returned
}
}
var myTest:ThisTest = new ThisTest();
var myFunc:Function = myTest.bar();
trace(this); // output: [object global]
myFunc();
/* output:
foo's this: [object ThisTest]
num: 3 */
The last two lines of code show that the this reference in the bound method foo() still
points to an instance of ThisTest class, even though the
this reference in the line just before
it points to the global object. Moreover, the bound method stored in the
myFunc variable still
has access to the member variables of the ThisTest class. If this same code is run in
ActionScript 2.0, the
this references would match and the num variable would be undefined.
One area where the addition of bound methods is most noticeable is with event handlers,
because the
addEventListener() method requires that you pass a function or method as an
argument. For more information, see “Listener function defined as a class method”
on page 359.