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

后端 未结 30 2777
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:55

    modified @Matthew answer. Here I can pass any number of parameters to function as usual (not array). Also 'Something' is not hardcoded into:

    function createObject( constr ) {   
      var args =  arguments;
      var wrapper =  function() {  
        return constr.apply( this, Array.prototype.slice.call(args, 1) );
      }
    
      wrapper.prototype =  constr.prototype;
      return  new wrapper();
    }
    
    
    function Something() {
        // init stuff
    };
    
    var obj1 =     createObject( Something, 1, 2, 3 );
    var same =     new Something( 1, 2, 3 );
    

提交回复
热议问题