I have an array with would simbolize parameters of a function.
For Example:
var params = ['name', 'age', 'email'];
and this information is created by another endpoint which return this array. and from this array I would like to create a function like this:
function (name, age, email) {
//...
//my custom code
return result;
}
So as you can see I would like to automatically create functions and use each array element as an argument to that function.
Is there any way to achieve that without using eval?
It seems new Function('name', 'age', 'email', 'fn body') can't be generated on the fly as well.
Thanks in advance
-
1What you want to do doesn't make any sense. There's no point in "creating" functions with named parameters. What is the real problem here?Alex Turpin– Alex Turpin2011年10月27日 14:44:31 +00:00Commented Oct 27, 2011 at 14:44
-
Do you really need to do this ? You can just expect an array or object as a parameter, and get what you need from there.Radoslav Georgiev– Radoslav Georgiev2011年10月27日 14:49:36 +00:00Commented Oct 27, 2011 at 14:49
3 Answers 3
var a = Function.apply( {}, ["name", "age", "email", "return email;"] );
/*function anonymous(name,age,email) {
return email;
}*/
a(1,2,3);
//3
This has no concrete benefits over eval though and what you are trying to do could probably be done differently without needing to evaluate strings into code on the fly
Comments
You can use .apply(). Make sure the function body is the last member of the array.
Function.apply( null, your_array );
Comments
If you want to call a function with an array of parameters, use apply. For example:
function foo(a, b, c) {
alert(a + b + c);
}
foo.apply(null, [1, 2, 3]);