new Function() with variable parameters

前端 未结 10 657
傲寒
傲寒 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条回答
  •  萌比男神i
    2020-12-25 11:58

    new Function(...)
    

    Declaring function in this way causes the function not to be compiled, and is potentially slower than the other ways of declaring functions.

    Let is examine it with JSLitmus and run a small test script:

    
    
    

    What I did above is create a function expression and function constructor performing same operation. The result is as follows:

    FireFox Performance Result

    FireFox Performance Result

    IE Performance Result

    IE Performance Result

    Based on facts I recommend to use function expression instead of function constructor

    var a = function() {
     var result = 0;
     for(var index=0; index < arguments.length; index++) {
      result += arguments[index];
     }
     return result;
     }
    alert(a(1,3));
    

提交回复
热议问题