LiLacTac LiLacTac - 2 months ago 5x
Javascript Question

How to call javascript function from string with function body and send multiple parameters?

I try to call a function from string with body of the function. I know only parameter names and can pass parameters to function.

I tried this way

function callFunction(body, paramNames, params) {
return new Function(paramNames, body)(params);

It only works for one parameter. How can I do it for several parameters?



If I understand you right, you want dynamically create functions, and pass parameters to it. Usually it done in two different steps: 1 - create the function, 2 - call it.

Here is the code

function createFunction(body, paramNames) {
  return new Function(paramNames, body);

    var func1 = createFunction("return a + 1;", ["a"]);
    var func2 = createFunction("return a + b;", ["a","b"]);
    $("#multipleParam").text(func2.apply(this, [1, 2]));