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

后端 未结 30 3387
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:08

    An improved version of @Matthew's answer. This form has the slight performance benefits obtained by storing the temp class in a closure, as well as the flexibility of having one function able to be used to create any class

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

    This would be used by calling applyCtor(class, [arg1, arg2, argn]);

提交回复
热议问题