Skip to content

Instantly share code, notes, and snippets.

@upangka
Last active January 2, 2020 10:01
Show Gist options
  • Save upangka/4749a73dc1753e7d0bb6a9ccd1a6bfc1 to your computer and use it in GitHub Desktop.
Save upangka/4749a73dc1753e7d0bb6a9ccd1a6bfc1 to your computer and use it in GitHub Desktop.
javascript 公共属性使用
let obj = {
	name: "Q10Viking"
}

console.log(obj)
// {name: "Q10Viking"}
let ano = {
	...obj,
  ['hobby1']: "keras",
  'hobby2': "Diangle",
  hobby3: 'tensflow'
}
console.log(ano,ano.hobby1)
// {name: "Q10Viking", hobby1: "keras", hobby2: "Diangle", hobby3: "tensflow"}

Example

before

let obj = null
      switch (type) {
        case 0:
          // 卡余额
          obj = {
            moneyDis: this.model.presentText,
            reduce: this.inputValue,
            userId: this.model.userId,
            cardId: this.model.cardId,
            cardNo: this.model.cardNo,
            message: this.desc,
            cardType: this.model.cardType
          }
          break
        case 1:
          // 兑换商品次数
          obj = {
            countDis: this.model.presentText,
            reduce: this.inputValue,
            userId: this.model.userId,
            cardId: this.model.cardId,
            cardNo: this.model.cardNo,
            message: this.desc,
            cardType: this.model.cardType,
            type: 1
          }
          break
        case 2:
          // 兑换门店次数
          obj = {
            countDis: this.model.presentText,
            reduce: this.inputValue,
            userId: this.model.userId,
            cardId: this.model.cardId,
            cardNo: this.model.cardNo,
            message: this.desc,
            cardType: this.model.cardType
          }
          break
        default:
          break
      }

after 优化之后

let commonAttr = {
        reduce: this.inputValue,
        userId: this.model.userId,
        cardId: this.model.cardId,
        cardNo: this.model.cardNo,
        message: this.desc,
        cardType: this.model.cardType,
        type: type
      }
      let obj = null
      switch (type) {
        case 0:
          // 卡余额
          obj = {
            ...commonAttr,
            moneyDis: this.model.presentText
          }
          break
        case 1:
          // 兑换商品次数
          obj = {
            ...commonAttr,
            countDis: this.model.presentText
          }
          break
        case 2:
          // 兑换门店次数
          obj = {
            ...commonAttr,
            countDis: this.model.presentText
          }
          break
        default:
          break
      }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment