var func = function(){};
var funcName = "func";
funcName.call();
I'm looking forward to some useful feature of Function
var func = function(){};
var funcName = "func";
funcName.call();
I'm looking forward to some useful feature of Function
You can use string identifiers for object property names using square bracket notation:
obj['identifier'] === obj.identifier
however, the only context in which you can access variables as object properties is for global variables since they are added as properties of the global (window in a browser) object:
var global = this;
var name = 'fred';
alert(global['name']); // fred
You can't access the variable object of any other execution context, but you can use eval to evaluate strings:
alert( eval('name'))
but that is strongly recommended against. Use object properties instead with square bracket notation.
If you are thinking of using user input to select a function to apply, some users might find an obnoxious use for that functionality (*), and it might be safer to assign the functions as values of a hash, perhaps as follows:
(*) Then again, visitors can edit their copy of the received javascript of a site at will so maybe this is moot.
function rotate(){
rotate an image;
}
function resize(){
resize an image;
}
operations = { 'rotate': rotate, 'resize': resize };
...
try {
(operations[userChoice])();
} catch(e){ console.log(e); } // or maybe tell the user there is no such function
Note how the use of an operations object limits what the userChoice can call.
I know this isn't exactly what you're asking about, but it may be a better option in some instances.
Instead of using the name of the function as a string, you can also deal directly with references to the function itself.
That would look like this:
function func() { // normal function definition
}
var func2 = function() {}; // anonymous function
var function_to_use = func; // works with normal functions
function_to_use();
function_to_use = func2; // as well as anonymous ones
function_to_use();