4

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

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's not limited to the global scope(but out of scope for this question) but I would always try to avoid it. It can break after minifying the code and searching for unused functions becomes impossible in larger projects. Using a 'dictionary' object is not much more work and very readable. - answer is good though.
8

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

Comments

1

if you put the functions in an array:

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

Call it like this:

functions['play'+number]();

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.