11

I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.

ex.

function A:

add(new Array("hello", some function));

function B:

public function b(args:Array) {
    var myString = args[0];
    var myFunc = args[1];
}

3 Answers 3

28

Simply pass the function name as an argument, no, just like in AS2 or JavaScript?

function functionToPass()
{
}

function otherFunction( f:Function )
{
    // passed-in function available here
    f();
}

otherFunction( functionToPass );
Sign up to request clarification or add additional context in comments.

Comments

7

This is very easy in ActionScript:

function someFunction(foo, bar) {
   ...
}

function a() {
    b(["hello", someFunction]);
}

function b(args:Array) {
    var myFunc:Function = args[1];
    myFunc(123, "helloworld");
}

Comments

2

You can do the following:

add(["string", function():void
{
trace('Code...');
}]);

...or...

...
add(["string", someFunction]);
...

private function someFunction():void
{
trace('Code...');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.