new Function() with variable parameters

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)