Ale*_*ory 5 javascript class spread-syntax
基本上这就是我想要完成的事情.
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)Run Code Online (Sandbox Code Playgroud)
有没有办法传播这样的对象来填充一个类?
如果您正在使用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)Run Code Online (Sandbox Code Playgroud)
有一个提议(目前处于第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)Run Code Online (Sandbox Code Playgroud)