Search code examples
javascriptargumentsargument-passingecmascript-5splat

splat over JavaScript object (with new)?


How do I splat across objects without using ECMA6 features?

Attempt

function can(arg0, arg1) {
    return arg0 + arg1;
}

function foo(bar, haz) {
    this.bar = bar;
    this.haz = haz;
}

myArgs = [1,2];

With can I can just do:

can.apply(this, myArgs);

When trying with foo:

new foo.apply(this, myArgs);

I get this error (because I'm calling new):

TypeError: function apply() { [native code] } is not a constructor

Solution

  • Using Object.create

    function foo(bar, haz) {
        this.bar = bar;
        this.haz = haz;
    }
    
    x = Object.create(foo.prototype);
    myArgs = [5,6];
    foo.apply(x, myArgs);
    
    console.log(x.bar);