- This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
Viewing 6 posts - 1 through 6 (of 6 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Function name as variable?
Is it possible to use a variable as a function name?
For example:
var string = "my_function";
string();
When I try to use that, I get an error that string is not a function, but there is a function named as that?
Why wouldn’t you just call `my_function()`?
What you can do is this:
var newVariable = function () {
// your stuff
});
newVariable();
I have to make it dynamic because I’m calling it from a click and checking some things before deciding which function to call. For example I’m checking screen size and then calling functions based on that as well as another value. The two put together make up the existing function name.
Couldn’t you use a Switch statement to determine which to call?
var string = “my_function”;
switch(string)
{
case “function_1”:
function_1();
break;
case “function_2”:
function_2();
break;
default:
function_default();
}
Then, if you wanted to add another possibility, all you really have to do is add a case.