简体   繁体   中英

how to execute javascript function when i send its name as string dynamically with out parameters

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

one simple way

eval("SomeFunction()");

or

var funcName = "SomeFunction";
var func == window[funcName];
func();

危险,但您可以使用eval(method_name+"()")

are you talking about ´eval()´??

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

Hope this helps;

function a() { 
   console.log('yeah!'); 
}

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

this[funcName]();

如果该函数是全局函数,则应在浏览器中执行window[funcName]()

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM