【问题标题】:Using one object value in another value on the same object Javascript [duplicate]在同一对象的另一个值中使用一个对象值Javascript [重复]
【发布时间】:2021-10-27 16:29:06
【问题描述】:

我的问题有点简单,但是IDK如果我没有用正确的关键字进行搜索,但我的问题是:

在 JS/TS 中定义对象时,如何将 obj 中的一个值用于另一个键,例如:

const person = {
  firstName: 'Régis',
  middleName: 'Faria',
  fullName: `${firstName + middleName}` // Here is where IDK how to do it. I've tried with 'this.' but no success
}

希望有人可以帮助我。提前致谢!!

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    用 firstName 和 middleName 构造对象,然后添加 fullName:

    const person = {
      firstName: 'Régis',
      middleName: 'Faria',
    }
    person.fullName = `${person.firstName}  ${person.middleName}`;
    

    【讨论】:

    • 谢谢。我正在考虑在声明中这样做......但我想这是不可能的哈哈
    【解决方案2】:

    要使用this关键字,你必须有一个对象的实例,为此,你可以创建一个Person类并初始化一个person

    class Person {
      constructor({ firstName, middleName }) {
        this.firstName = firstName
        this.middleName = middleName
      }
      get fullName() {
        return `${this.firstName} ${this.middleName}`
      }
    }
    
    const person = new Person({
      firstName: 'Régis',
      middleName: 'Faria',
    })
    
    console.log(person.fullName)

    否则,必须先设置firstNamemiddleName

    const firstName = 'Régis'
    const middleName = 'Faria'
    const person = {
      firstName,
      middleName,
      fullName: `${firstName} ${middleName}`
    }
    
    console.log(person.fullName);

    我个人更喜欢使用 TypeScript:

    // create a Person type
    type Person {
      firstName: string
      lastName: string
      fullName: string
    }
    
    // then it's ok to have variable
    const firstName = 'Régis'
    const middleName = 'Faria'
    
    // then your person
    const person: Person = {
      firstName,
      middleName,
      fullName: `${firstName} ${middleName}`
    }
    console.log(person.fullName)
    

    【讨论】:

    • 感谢您的完整回答。我希望通过对象声明来实现这一点,但我想这是不可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2021-10-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多