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

后端 未结 30 3409
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 01:03

    Make an anonymous prototype and apply the Something prototype to it using the arguments and then create a new instance of that anonymous prototype. The one disadavantage of this is it will not pass the s instanceof Something check, though it is identical, it is basically an instance of a clone.

    function Something(){
        // init stuff
    }
    function createSomething(){
        return new (function(){Something.apply(this, arguments)});
    }
    var s = createSomething(a,b,c); // 's' is an instance of Something
    

提交回复
热议问题