javascript - new Function() with variable parameters -


i need create function variable number of parameters using new function() constructor. this:

args = ['a', 'b']; body = 'return(a + b);';  myfunc = new function(args, body); 

is possible without eval()?


thank much, guys! actually, a+b not primary concern. i'm working on code process , expand templates , needed pass unknown (and variable) number of arguments function introduced local variables.

for example, if template contains:

<span> =a </span>  

i need output value of parameter a. is, if user declared expanding function

var expand = tplcompile('template', a, b, c)  

and calls

expand(4, 2, 1)  

i need substitute =a 4. , yes, i'm aware function similar eval() , runs slow don't have other choice.

you can using apply():

args = ['a', 'b', 'return(a + b);']; myfunc = function.apply(null, args); 

without new operator, function gives same result. can use array functions push(), unshift() or splice() modify array before passing apply.

you can pass comma-separated string of arguments function:

args = 'a, b'; body = 'return(a + b);';  myfunc = new function(args, body); 

on side note, aware of arguments object? allows arguments passed function using array-style bracket notation:

myfunc = function () {     var total = 0;      (var i=0; < arguments.length; i++)         total += arguments[i];      return total; }  myfunc(a, b); 

this more efficient using function constructor, , more appropriate method of achieving need.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -