【问题标题】:How to spread an object into a classes properties in JavaScript如何将对象传播到 JavaScript 中的类属性中
【发布时间】:2018-02-26 15:13:33
【问题描述】:

基本上这就是我想要完成的。

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)

有没有办法传播这样的对象来填充类?

【问题讨论】:

    标签: javascript class spread-syntax


    【解决方案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)

    有一个 proposal(目前处于第 3 阶段,因此很可能在 ES2018 中,并且受到转译器的广泛支持)在对象初始值设定项中传播对象属性,但这不适用于对象已经存在的情况存在。

    【讨论】:

    • @AlexCory:哈哈,我们都做过这样的事情。 :-)
    【解决方案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)

    【讨论】:

      【解决方案3】:

      这就是你要找的吗?

      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)

      【讨论】:

        【解决方案4】:

        我个人更喜欢使用单独的方法,因为在 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)
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2021-02-12
          • 2021-03-15
          • 2020-03-09
          • 2022-07-21
          • 2020-06-28
          • 2015-11-15
          • 2020-01-09
          • 1970-01-01
          • 2022-12-03
          相关资源
          最近更新 更多