Question

Is there any way to concat a js function name? right now I have this:

switch (playId) {
        case "11":
            play11();
            break;
        case "22":
            play22();
            break;
        case "33":
            play33();
            break;
        case "44":
            play44();
            break;
        default:
            break;
    }

and I want to do somthing like this:

var function = "play" + playId + "()";

and call it.. what is the best way if possible?


Solution:

What I did with the help of thefourtheye and xdazz is very simple:

var playFunction = window["play" + playId];
    playFunction();
Was it helpful?

Solution

If these functions are defined in global scope, then you could get them from the global object:

var foo = window["play" + taskId];

Otherwise you could put them together in an object like another answer suggested.

OTHER TIPS

The best way is to put them in an object like this

var functions = {
    11: play11,
    22: play22,
    33: play33,
    44: play44
};

and then invoke it like this

functions[taksId]();

Since you don't want to fail if taskId is not found, you can do

if (functions.hasOwnProperty(taskId)) {
    functions[taksId]();
}

if you put the functions in an array:

var functions = {
    'play1':function(){},
    'play2':function(){}
}

Call it like this:

functions['play'+number]();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top