new Function() with variable parameters

前端 未结 10 681
傲寒
傲寒 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 12:03

    @AndyE's answer is correct if the constructor doesn't care whether you use the new keyword or not. Some functions are not as forgiving.

    If you find yourself in a scenario where you need to use the new keyword and you need to send a variable number of arguments to the function, you can use this

    function Foo() {
      this.numbers = [].slice.apply(arguments);
    };
    
    
    var args = [1,2,3,4,5]; // however many you want
    var f = Object.create(Foo.prototype);
    Foo.apply(f, args);
    
    f.numbers;          // [1,2,3,4,5]
    f instanceof Foo;   // true
    f.constructor.name; // "Foo"
    

    ES6 and beyond!

    // yup, that easy
    function Foo (...numbers) {
      this.numbers = numbers
    }
    
    // use Reflect.construct to call Foo constructor
    const f =
      Reflect.construct (Foo, [1, 2, 3, 4, 5])
    
    // everything else works
    console.log (f.numbers)          // [1,2,3,4,5]
    console.log (f instanceof Foo)   // true
    console.log (f.constructor.name) // "Foo"

提交回复
热议问题