Use of .apply() with 'new' operator. Is this possible?

后端 未结 30 3188
Happy的楠姐
Happy的楠姐 2020-11-22 00:39

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

30条回答
  •  误落风尘
    2020-11-22 00:54

    If your environment supports ECMA Script 2015's spread operator (...), you can simply use it like this

    function Something() {
        // init stuff
    }
    
    function createSomething() {
        return new Something(...arguments);
    }
    

    Note: Now that the ECMA Script 2015's specifications are published and most JavaScript engines are actively implementing it, this would be the preferred way of doing this.

    You can check the Spread operator's support in few of the major environments, here.

提交回复
热议问题