Search code examples
javascriptstring-concatenation

Concatenation function name in js


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();

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.