Search code examples
flashactionscript-3

AS3 - something like arguments.caller?


Is there something that returns a reference to the object that called the function?

For example, I have..

public function getSquadLocation(squadID:int):Location {
//stuff
}

This gets called from other classes - for example:

getSquadLocation(selectedSquad);

where selectedSquad is a variable of the class that calls the function. I've being repeating this many times, would it be possible to specify the default value as something like...

public function getSquadLocation(squadID:int = arguments.caller.selectedSquad){

Thanks


Solution

  • No, you can't access the "caller" 'implicitly'. Quoting the relevant page from the ActionScript 3 documentation by Adobe:

    Unlike previous versions of ActionScript, ActionScript 3.0 has no arguments.caller property. To get a reference to the function that called the current function, you must pass a reference to that function as an argument.

    What you can do, and it would arguably be a "less volatile" alternative, is to simply pass the "caller" to a method as an argument, i.e. explicitly. There are many advantages to this approach, as you may discover in the long run:

    • Porting the code to other platforms where function caller information is not exposed, is less troublesome.

    • Passing required caller information explicitly as function arguments (on the stack) may yield more performance.

    • Passing caller information explicitly to a function reads better as the dependency of the implementation on the caller is made explicit, assisting in readability and understanding of the code.