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

后端 未结 30 2721
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

    Suppose you've got an Items constructor which slurps up all the arguments you throw at it:

    function Items () {
        this.elems = [].slice.call(arguments);
    }
    
    Items.prototype.sum = function () {
        return this.elems.reduce(function (sum, x) { return sum + x }, 0);
    };
    

    You can create an instance with Object.create() and then .apply() with that instance:

    var items = Object.create(Items.prototype);
    Items.apply(items, [ 1, 2, 3, 4 ]);
    
    console.log(items.sum());
    

    Which when run prints 10 since 1 + 2 + 3 + 4 == 10:

    $ node t.js
    10
    

提交回复
热议问题