Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want execute javascript function which the name is coming as a string dynamically. ansd i dont need to pass any parameters while executing the function.

Please can any one guide me how to achieve this?

Regards, Kamesh

share|improve this question
    
eval is evil, try to avoid it at all costs –  herby Dec 1 '11 at 15:29
    

7 Answers 7

one simple way

eval("SomeFunction()");

or

var funcName = "SomeFunction";
var func == window[funcName];
func();
share|improve this answer

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

share|improve this answer
    
it is working in FF but its not working in IE –  kamesh Dec 1 '11 at 16:24

are you talking about ´eval()´??

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

Hope this helps;

share|improve this answer
function a() { 
   console.log('yeah!'); 
}

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

this[funcName]();
share|improve this answer

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

share|improve this answer
    
You chould check if it exists with if ("function" === typeof window[funcName]) –  herby Dec 1 '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 1 '11 at 16:43

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.