是否可以避免“此”分配列表,而以某种方式“传播”构造函数中命名的所有args?
class MyClass {
constructor(arg1, arg2, arg3, arg4, arg5) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
this.arg4 = arg4;
this.arg5 = arg5;
}
}
答案 0 :(得分:1)
您可以使用一组键来迭代参数。
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);