I need to create a function with variable number of parameters using new Function()
constructor. Something like this:
args = ['a', 'b']; body = 'return(a + b);'; myFunc = new Function(args, body);
Is it possible to do it without eval()
?
Thank you very much, guys! Actually, a+b was not my primary concern. I'm working on a code which would process and expand templates and I needed to pass unknown (and variable) number of arguments into the function so that they would be introduced as local variables.
For example, if a template contains:
<span> =a </span>
I need to output the value of parameter a
. That is, if user declared expanding function as
var expand = tplCompile('template', a, b, c)
and then calls
expand(4, 2, 1)
I need to substitute =a
with 4
. And yes, I'm well aware than Function is similar to eval()
and runs very slow but I don't have any other choice.
A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions. For example: function example(parameter) { console.
A JavaScript function does not perform any checking on parameter values (arguments).
A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.
You can do this using apply():
args = ['a', 'b', 'return(a + b);']; myFunc = Function.apply(null, args);
Without the new
operator, Function
gives exactly the same result. You can use array functions like push(), unshift() or splice() to modify the array before passing it to apply.
You can also just pass a comma-separated string of arguments to Function:
args = 'a, b'; body = 'return(a + b);'; myFunc = new Function(args, body);
On a side note, are you aware of the arguments object? It allows you to get all the arguments passed into a function using array-style bracket notation:
myFunc = function () { var total = 0; for (var i=0; i < arguments.length; i++) total += arguments[i]; return total; } myFunc(a, b);
This would be more efficient than using the Function constructor, and is probably a much more appropriate method of achieving what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With