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

后端 未结 30 2720
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:16

    A revised solution from @jordancpaul's answer.

    var applyCtor = function(ctor, args)
    {
        var instance = new ctor();
        ctor.prototype.constructor.apply(instance, args);
        return instance;
    }; 
    

提交回复
热议问题