1

I have 6 functions, called callClip1, callClip2, callClip3 and so on.

I had planned on writing out 6 else/if statements to call each of these when I need to, but I thought it could (possibly) be done another way. Could I call one function called "callClip" and add a variable to the end of it that I set elsewhere? So if the variable was set to 3, it would put callClip + 3 together and call that function?

Thanks

2 Answers 2

4

This could be done with a switch block:

Used as: callClip(1);

function callClip(number:int):void
{
    switch(number)
    {
        case 1:
            callClip1();
            break;
        case 2:
            callClip2();
            break;
        case 3:
            callClip3();
            break;
        case 4:
            callClip4();
            break;
        case 5:
            callClip5();
            break;
        case 6:
            callClip6();
            break;
    }
}

Although I wouldn't recommend it, this could also be implemented as:

function callClip(number:int):void
{
    this["callClip" + number]();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice I was just about to suggest your second idea, and also would not recommend it :)
Agree I think generally though instead of having a bunch of functions there should probably just be one that has this type of switch in it to change the functionality rather than having a bunch of copies of a function and the need to both update the switch statement and create the new function. Good answer if there's a good reason to be doing this (like callClip1-6 all have very variable functionality within them).
2

Adding to Jason's answer, you could also do this:

// Store references to each method.
var methods:Vector.<Function> = new <Function>[
    callClip1, callClip2, callClip3,
    callClip4, callClip5, callClip6
];


// Call relevant callClip function.
function callClip(num:int):void
{
    methods[num-1]();
}

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.