LiLacTac LiLacTac - 3 months ago 13
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?

Thanks

Answer

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);
}

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