简体   繁体   中英

How to use variable instead of function name in JavaScript

I would like to know whether there is a method to use variable name instead of function. That is,

function dialog(a,b) {
    a(b);
}

Example: If user pass 'alert' to a and the content to b . Then it should alert b .

If a is 'confirm' , then it should confirm b .

I can use switch case or if else, but I would like to know the above is possible.

I think you're looking for the eval() method , however it can lead to insecurities if you aren't careful.

You could just have the users supply them the function itself if, in your example, they passed in the raw function as a , but I'm assuming you want them to pass a string which names a function that gets used.

function(a, b) {
  eval(a + '(' + b + ')');
}

Use .call()

function callme(a,b){
  return a.call(null, b);
};

var func = function(c) {
  return c;
};

alert(callme(func, "test"));

Any function you pass to callme will execute there. The first argument is the context, so you could pass this if you need to. Pass null otherwise.

In your case, alert/confirm can be passed. If you don't need to return something, just do an empty return at the end.

Don't use eval , for the love of all things good.

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