Uses for arguments
The arguments magic variable has been around since the AS2 days. It used to be more useful than it is in AS3, but don’t overlook it completely!
The basic usefulness of arguments is less useful now that we have var args. Here’s how it went in AS2:
function noVarArgs(a:Number, b:Number): void { arguments[0]; // a, or you could just use a arguments[1]; // b, or you could just use b arguments[2]; // third argument arguments[3]; // fourth argument }
Now you can do this a lot more simply and cleanly in AS3:
function varArgs(a:Number, b:Number, ... args) { a; // a b; // b args[0]; // third argument args[1]; // fourth argument }
Note that any arguments not provided will be undefined. In AS2, arguments also had two fields: callee and caller. These were references to the function that was called and the function that called it. You could do some real hackery (and debugging) by checking which function called you. The caller field is gone in AS3 and JavaScript and those possibilities are gone with it. The callee field remains though, and proves useful:
private function onImageLoaded(ev:Event): void { removeEventListener(Event.COMPLETE, arguments.callee); }
If the name of the callback ever changes, you won’t have to change the removeEventListener call. That’s pretty minor, but this isn’t:
loader.addEventListener( Event.COMPLETE, function(ev:Event): void { removeEventListener(Event.COMPLETE, arguments.callee); } );
In this case the function has no name. Sure, you could give it a name, but it’d be a lot more awkward. You’d probably do what I used to do and use a temporary variable:
var onComplete:Function = function(ev:Event): void { removeEventListener(Event.COMPLETE, onComplete); }; loader.addEventListener(Event.COMPLETE, onComplete);
There’s no need for that variable since it’s a constant. You could declare it as a const, but the damage is the same.
While the usage for arguments is minor, I still find this little tip helpful. I hope you do too.
#1 by Robert Penner on September 16th, 2009 ·
A completely generic way is ev.currentTarget.removeEventListener(ev.type, arguments.callee);
#2 by jackson on September 16th, 2009 ·
Good point. I should have cross-linked this article to another one I wrote with that super-generic way of removing.