2
var func = function(){};
var funcName = "func";
funcName.call();

I'm looking forward to some useful feature of Function

freddiefujiwara
  • 57,041
  • 28
  • 76
  • 106
  • 2
    If it's in the window scope you can do `window[funcName]()`. – elclanrs Jun 12 '13 at 02:41
  • 2
    if you attached it to say window for example, you could say `window.func=function(){};` then `window['func']();` but I wouldn't recommend it. What is the actual problem you are trying to solve? – asawyer Jun 12 '13 at 02:42

3 Answers3

1

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

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.

Paul
  • 26,170
  • 12
  • 85
  • 119
0

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();
jcsanyi
  • 8,133
  • 2
  • 29
  • 52