1

How can i call a function form a variable.

var upfunction = init;
//or
var upfunction = init();

I have tried the above code and it does not work. I want to be able to call that variable from a keypress and change the variables function. For example.

function init(){
   //Do whatever
}

function init2(){
   //Do another thing
}

var upfunction = init();
if (Key.getCode() == Key.UP)
{
    upfunction;
} 

Then later doing

upfunction = init2();

That way i could change the function without having much code. Sorry if this is a noob question but all i do is copy and paste code i have found.

1 Answer 1

1

You're almost right with what you've got... just remember that to call a function you need to include the brackets afterwards: 'upFuntion();'. Brackets are also needed when defining the function. The brackets will contain any function parameters.

But to refer to the function (such as when assigning it to a variable) you don't use the brackets: 'upFunction = init;'

So your example would look like this:

function init1():Void {
    trace("hello this is init1");
}

function init2():Void {
    trace("hey, this is init2");
}

var upFunction:Function = init1;//type declaration is optional but recommended

upFunction();// hello this is init1

upFunction = init2;

upFunction();//hey, this is init2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.