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();
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();
Share
Improve this question
edited Apr 24, 2014 at 9:04
ParPar
asked Apr 24, 2014 at 8:23
ParParParPar
7,5697 gold badges45 silver badges56 bronze badges
3 Answers
Reset to default 8If 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.
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]();