javascript using string of function name to call function

Snippet

Have a string of a function name and want to call the function whose name is the string.

// Consider:
 
var searchFn = "fnCallBack";
 
// want to do this (which fails)
 
searchFn(name);
 
// use this:
 
eval(searchFn)(name);
 
// or this:
 
var fn = new Function("term", "return " + searchFn + "(term);");
fn(name);
 
// be calling this:
 
fnCallBack(name);

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.