0

Is it possible to avoid "this" assignment list and somehow "spread" all the args named in constructor?

class MyClass {
    constructor(arg1, arg2, arg3, arg4, arg5) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
        this.arg4 = arg4;
        this.arg5 = arg5;
    }

}
Bambino Negro
  • 115
  • 1
  • 8

1 Answers1

1

You could take an array of keys an iterate the arguments.

class MyClass {
    constructor(...args) {
        var keys = ['arg1', 'arg2', 'arg3', 'arg4', 'arg5']
        keys.forEach((k, i) => this[k] = args[i]);
    }
}

var instance = new MyClass('a', 'b');

console.log(instance);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392