HUWWW
而是传入一个对象,然后使用Object.assign:class C { constructor(obj) { Object.assign(this, obj); }}const c = new C({ a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' });console.log(c);注意constructor必须是小写。您还可以使用参数休息语法,让您在调用时避免重复new C:class C { constructor(...args) { const props = ['a', 'b', 'c', 'd', 'e']; const obj = Object.fromEntries( args .slice(0, 5) .map((val, i) => [props[i], val]) ); Object.assign(this, obj); }}const c = new C('a', 'b', 'c', 'd', 'e');console.log(c);作为BERGI笔记,你也可以调用Array.prototype.entries上props的更少的代码:class C { constructor(...args) { const props = ['a', 'b', 'c', 'd', 'e']; for (const [i, prop] of props.entries()) { this[prop] = args[i]; } }}const c = new C('a', 'b', 'c', 'd', 'e');console.log(c);