2

I want execute JavaScript function which the name is coming as a string dynamically. I don't need to pass any parameters while executing the function.

Please can any one guide me how to achieve this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kamesh
  • 77
  • 1
  • 10
  • eval is evil, try to avoid it at all costs –  Dec 01 '11 at 15:29
  • Check this threads http://stackoverflow.com/questions/676721/calling-dynamic-function-with-dynamic-parameters-in-javascript and http://stackoverflow.com/questions/5618007/how-to-call-the-javascript-function-dynamically – dku.rajkumar Dec 01 '11 at 15:33

7 Answers7

1

one simple way

eval("SomeFunction()");

or

var funcName = "SomeFunction";
var func == window[funcName];
func();
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
0

dangerous but you could use eval(method_name+"()")

Leon
  • 4,532
  • 1
  • 19
  • 24
0

are you talking about ´eval()´??

var foo = "alert('bar')";
eval(foo);

Hope this helps;

pleasedontbelong
  • 19,542
  • 12
  • 53
  • 77
0
function a() { 
   console.log('yeah!'); 
}

var funcName = 'a'; // get function name

this[funcName]();
defuz
  • 26,721
  • 10
  • 38
  • 60
0

If the function is global, you should do window[funcName]() in browser.

  • You chould check if it exists with `if ("function" === typeof window[funcName])` –  Dec 01 '11 at 15:32
  • window[funcName]() it is working in Firefox but not working in IE8 Iam getting error in IE8 is expected identifier – kamesh Dec 01 '11 at 16:43
0

Using eval is the worst way imaginable. Avoid that at all costs.

You can use window[functionname]() like this:

function myfunction() {
    alert('test');
}

var functionname = 'myfunction';
window[functionname]();

This way you can optionally add arguments as well

Tim S.
  • 13,597
  • 7
  • 46
  • 72
0

Perhaps a safer way is to do something like this (pseudo code only here):

function executer(functionName)
{
  if (functionName === "blammo")
  {
    blammo();
  }
  else if (functionName === "kapow")
  {
    kapow();
  }
  else // unrecognized function name
  {
    // do something.
  }

You might use a switch statement for this (it seems like a better construct):

switch (functionName)
{
  case "blammo":
    blammo();
    break;

  case "kapow":
    kapow();
    break;

  default:
    // unrecognized function name.
}

You can optimize this by creating an array of function names, searching the array for the desired function name, then executing the value in the array.

DwB
  • 37,124
  • 11
  • 56
  • 82