The AS2 analogue of Java’s anonymous inner class construct is common for event handlers and looks like this:
class Bar {
var notifier;
public function foo(Void):Void {
var loadListener = new Object();
loadListener.numLoaded = 0;
loadListener.handleEvent = function(evt) {
if (evt.type == "complete") {
trace("all done");
notifier.notify(); // < -- won't work
}
};
myLoader.addEventListener("progress", loadListener);
}
}
In this case the loadListener is an instance of an anonymous class that is declared and used inside the foo method of another class. Let's say, however, that we want loadListener's handleEvent method to have access to notifier, which is a member of the enclosing class. Just referencing notifier or this.notifier within the handleEvent body won't work, because "this" in that context means the loadListener instance itself. What we need to do is provide an explicit reference to the enclosing class context outside the loadListener declaration:
class Bar {
var notifier;
public function foo(Void):Void {
// here we set up a reference to the enclosing class instance
var thiz = this;
var loadListener = new Object();
loadListener.numLoaded = 0;
loadListener.handleEvent = function(evt) {
if (evt.type == "complete") {
trace("all done");
thiz.notifier.notify(); // < -- this works
}
};
myLoader.addEventListener("progress", loadListener);
}
}
By declaring a local variable "thiz" that contains a reference to "this" at the place it's declared, that is, the Bar (enclosing class) instance, we're able to access that enclosing class through thiz in the inner class methods. I chose the name "thiz" because it's kind of (but not really) similar to the way "clazz" is sometimes used in reflection code in Java.