Skip to content Skip to sidebar Skip to footer

Can I Use The Value Of A Variable To Initiate A Function?

Possible Duplicate: Calling a JavaScript function named in a variable I want to use the value of a variable as the call to initiate a function, but I'm not sure if it is possibl

Solution 1:

You could do a few things:

//if the function is in the global scope:window["myFunction"](); 
//orvar functionName = "myFunction";
window[functionName]();

Or maintain your own map:

var functions = {
    myFunction: function() {
        ...
    },
    ...
    myOtherFunction: function() {
        ...
    }
};

Then either of the following will work:

functions.myFunction(); //will work
functions["myFunction"](); //will also work;

var functionName = "myFunction";
functions[functionName](); //also works

Of course, you can use eval:

eval(functionName + "()");

But eval is dangerous and I don't recommend it.

Based on your fiddle

Your right and left functions have been defined in the local scope of an anonymous function. This means that they are not part of the global window object. You should use the second method I described above (constructing your own map):

var directions = {
    right: function() {
        ...
    },
    left: function() {
        ...
    }
    ...
};

var direction = "right";
directions[direction]();

Post a Comment for "Can I Use The Value Of A Variable To Initiate A Function?"