new Function() with variable parameters

前端 未结 10 653
傲寒
傲寒 2020-12-25 11:38

I need to create a function with variable number of parameters using new Function() constructor. Something like this:

args = [\'a\', \'b\'];
bod         


        
10条回答
  •  既然无缘
    2020-12-25 11:55

    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.

提交回复
热议问题