[英]How to spread an object into a classes properties in JavaScript
基本上这就是我想要完成的。
class Person { constructor (obj) { this.first = '' this.last = '' this.age = '' if (obj) { Object.assign(this, ...obj) } } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ first: 'Alex', last: 'Cory', age: 27 }) console.log('Spreading: ', b)
有没有办法传播这样的对象来填充一个类?
如果您使用的是Object.assign
,则不使用扩展表示法; 只需删除...
:
class Person { constructor (obj) { this.first = '' this.last = '' this.age = '' if (obj) { Object.assign(this, obj) // <============ No ... } } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ first: 'Alex', last: 'Cory', age: 27 }) console.log('Spreading: ', b)
有一个提议 (目前处于第3阶段,很可能在ES2018中,并得到转发器的广泛支持),它在对象初始化器中对象属性传播,但这不适用于对象已存在的情况。
您可以使用解构并仅使用您需要的属性。
class Person { constructor ({ first = '', last = '', age = '' } = {}) { Object.assign(this, { first, last, age }); } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ first: 'Alex', last: 'Cory', age: 27, foo: 42 }) console.log('Spreading: ', b)
这是你在找什么?
class Person { constructor (obj) { this.firstName = '' this.lastName = '' this.age = '' if (obj) { Object.assign(this, obj) } } } const a = new Person() console.log('Not spreading: ', a) const b = new Person({ firstName: 'Alex', lastName: 'Cory', age: 27 }) console.log('Spreading: ', b)
我个人更喜欢使用单独的方法,因为在 JS 中不可能有多个构造函数。 在以下示例中,我使用返回新对象的static fromObject()
方法创建新对象。 因此,您可以保留普通构造函数并使用扩展语法创建新对象。
注意:我在这里使用打字稿。
export class Point {
readonly x: number
readonly y: number
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
static fromObject({x, y}: {x: number, y: number}) {
return new Point(x, y)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.