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

后端 未结 30 2723
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:59

    You could move the init stuff out into a separate method of Something's prototype:

    function Something() {
        // Do nothing
    }
    
    Something.prototype.init = function() {
        // Do init stuff
    };
    
    function createSomething() {
        var s = new Something();
        s.init.apply(s, arguments);
        return s;
    }
    
    var s = createSomething(a,b,c); // 's' is an instance of Something
    
    0 讨论(0)
  • 2020-11-22 00:59

    if you're interested in an eval-based solution

    function createSomething() {
        var q = [];
        for(var i = 0; i < arguments.length; i++)
            q.push("arguments[" + i + "]");
        return eval("new Something(" + q.join(",") + ")");
    }
    
    0 讨论(0)
  • 2020-11-22 00:59

    While the other approaches are workable, they're unduly complex. In Clojure you generally create a function that instantiates types/records and use that function as the mechanism for instantiation. Translating this to JavaScript:

    function Person(surname, name){
      this.surname = surname;
      this.name = name;
    }
    
    function person(surname, name){ 
      return new Person(surname, name);
    }
    

    By taking this approach you avoid the use of new except as described above. And this function, of course, has no issues working with apply or any number of other functional programming features.

    var doe  = _.partial(person, "Doe");
    var john = doe("John");
    var jane = doe("Jane");
    

    By using this approach, all of your type constructors (e.g. Person) are vanilla, do-nothing constructors. You just pass in arguments and assign them to properties of the same name. The hairy details go in the constructor function (e.g. person).

    It is of little bother having to create these extra constructor functions since they are a good practice anyhow. They can be convenient since they allow you to potentially have several constructor functions with different nuances.

    0 讨论(0)
  • 2020-11-22 01:00

    This one-liner should do it:

    new (Function.prototype.bind.apply(Something, [null].concat(arguments)));
    
    0 讨论(0)
  • 2020-11-22 01:00

    Thanks to posts here I've used it this way:

    SomeClass = function(arg1, arg2) {
        // ...
    }
    
    ReflectUtil.newInstance('SomeClass', 5, 7);
    

    and implementation:

    /**
     * @param strClass:
     *          class name
     * @param optionals:
     *          constructor arguments
     */
    ReflectUtil.newInstance = function(strClass) {
        var args = Array.prototype.slice.call(arguments, 1);
        var clsClass = eval(strClass);
        function F() {
            return clsClass.apply(this, args);
        }
        F.prototype = clsClass.prototype;
        return new F();
    };
    
    0 讨论(0)
  • 2020-11-22 01:01

    Here's a generalized solution that can call any constructor (except native constructors that behave differently when called as functions, like String, Number, Date, etc.) with an array of arguments:

    function construct(constructor, args) {
        function F() {
            return constructor.apply(this, args);
        }
        F.prototype = constructor.prototype;
        return new F();
    }
    

    An object created by calling construct(Class, [1, 2, 3]) would be identical to an object created with new Class(1, 2, 3).

    You could also make a more specific version so you don't have to pass the constructor every time. This is also slightly more efficient, since it doesn't need to create a new instance of the inner function every time you call it.

    var createSomething = (function() {
        function F(args) {
            return Something.apply(this, args);
        }
        F.prototype = Something.prototype;
    
        return function(args) {
            return new F(args);
        }
    })();
    

    The reason for creating and calling the outer anonymous function like that is to keep function F from polluting the global namespace. It's sometimes called the module pattern.

    [UPDATE]

    For those who want to use this in TypeScript, since TS gives an error if F returns anything:

    function construct(constructor, args) {
        function F() : void {
            constructor.apply(this, args);
        }
        F.prototype = constructor.prototype;
        return new F();
    }
    
    0 讨论(0)
提交回复
热议问题