2017-09-18 4 views
0

基本的にここで私が達成しようとしていることがあります。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)

クラスを移入するために、このようなオブジェクトを普及させる方法はあり ?

答えて

1

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)
オブジェクト初期化子内のプロパティの広がりをオブジェクトん(ES2018にあるととてもそう、広くtranspilersでサポートされている現在、ステージ3で、) proposalあり

、オブジェクトがすでに存在する状況には適用されません。

+0

私は –

+0

@AlexCoryすごい...今ダム感じる:LOL、我々はすべてのそのようなことをやりました。 :-) –

1

これはあなたが探しているものですか?

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)

2

あなたは解体を使用して、プロパティだけを取ることができる、あなたが必要です。

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)

関連する問題