I have a method which logs a message each time it is called. I would like this log message to indicate whether the method was called directly or invoked using super
in a child class.
class DoerOfWork {
public function doWork():void {
var calledWithSuper:Boolean;
calledWithSuper = ???;
trace("doWork called" + (calledWithSuper ? " (with super)." : "."));
}
}
class SlowerDoerOfWork extends DoerOfWork {
public override function doWork():void {
for (var i:Number = 0; i < 321684; i++) {
// wait a moment
}
super.doWork();
}
}
I hoped it would be possible to determine whether the class of this
had overridden the implementation of doWork
by comparing this.doWork
to DoerOfWork.prototype.doWork
.
Unfortunately this isn't possible. Unbound methods are not accessible anywhere in ActionScript (the specification lists two types of functions: function closures and bound methods). There don't even to be any properties on instances on MethodClosure
that could identify whether two are bound copies of the same method.
How can I check if a method has been overridden or use any other method to determine whether the currently-executing ActionScript method was called using super
or called directly?
You can get a reference to the currently-executing function as arguments.callee
. From the method this will be the MethodClosure
of DoerOfWork().doWork()
with this
. If doWork()
hasn't been overridden this will be equal to this.doWork
.
class DoerOfWork {
public function doWork():void {
var calledWithSuper:Boolean;
calledWithSuper = this.doWork == arguments.callee;
trace("doWork called" + (calledWithSuper ? " (with super)." : "."));
}
}
If you're running in non-strict mode, apparently this will disable argument count checking for the current function. (I haven't checked this myself, I'm not even sure how to disable strict mode in IntelliJ.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With