简体   繁体   中英

Javascript call function as string, with multiple parameters not using eval()

I am quite new to javascript, but I know you can call a function with it being represented by a string such that:

 var function_to_call = window[values['function']];
 //Where values['function']='functionName'

So far so good, then we have:

 if(typeof function_to_call == 'function'){
       if(values['parameters']!= '')
                function_to_call(values['parameters']);
       else function_to_call();
  };

Of course, this won´t work because the parameters come out as "parameter1, parameter2" all in one string so you end up with

function_to_call("parameter1, parameter2");

rather than

function_to_call(parameter1, parameter2);

any ideas? Appreciate your time!

EXPANDED:

The parameters passed to the function represent the "id" of elements in the page; so the function that is called will be trying to get those elements by doing:

document.getElementById(parameter1);
...some other things...
document.getElementById(parameter2);

I assume the parameter names represent global variables as well.

If so, you could split them into an Array, then .map() the Array into a new array of the related globals.

Then use .apply() to invoke the function with the array of arguments.

if (typeof function_to_call == 'function') {
     if(values['parameters']!= '') {
          var args = values['parameters'].split(",")
                                         .map(function(name) {
                                             return window[name.trim()];
                                         });
          function_to_call.apply(window, args);
     } else function_to_call();
}

The .trim() and .map() methods will need a shim for IE8... but this mainly shows how you could do it. As an alternative, you could pass a regex to .split() to take care of any spaces.

var args = values['parameters'].split(/\s*,\s*/)...
 if(typeof function_to_call == 'function'){
   if(values['parameters']!= '')
            setTimeout('function_to_call('.values['parameters'].');');
   else  setTimeout('function_to_call();',0);
  }

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