I have a really long winded switch case statement like this
switch(x){
case "a":
// call function a
a():
break;
case "b":
// call function b
a():
break;
case "c":
// call function c
c():
break;
}
Can’t i simply say
// If the x variable is set, call the corresponding function
If (x){
x();
}
The only reason its not working is because it thinks that im calling the function x(), but i want to use x as a placeholder for other functions. Is this possible?
It depends where your function is defined. If its defined in global scope, you can say:
if (window[x]) window[x]();If its part of an object which is in global scope, say:
then you can call it like:
window[obj][x]();This is to get you started. You should add null checks and whether its really a function or not in your final routine.
If you use jQuery, you can check by saying:
if (jQuery.isFunction(window[x])) window[x]();