如何重构两次使用的JavaScript函数

时间:2017-04-24 08:36:41

标签: javascript function

我有这两个条件

if (civility.labelKey === lady) {
  const contactType = this.contactTypes.find((type) => type.label_key === madam)
  this.onSelect({
    $event: { contactType }
  })
  this.contact.greetings = civility
} else {
  const contactType = this.contactTypes.find((type) => type.label_key === civility.labelKey)
  this.onSelect({
    $event: { contactType }
  })
}

我想分解(统一)这段代码:

this.onSelect({
    $event: { contactType }
  })

谁重复两次,你有解决方案吗?

1 个答案:

答案 0 :(得分:1)

你可以提取这样的函数:

function bindOnSelect(component, contactType){
    component.onSelect({
    $event: { contactType }
  })
}

然后调用该函数:

if (civility.labelKey === lady) {
      const contactType = this.contactTypes.find((type) => type.label_key === madam)
      bindOnSelect(this, contactType);
      this.contact.greetings = civility
    } else {
      const contactType = this.contactTypes.find((type) => type.label_key === civility.labelKey)
      bindOnSelect(this, contactType);
    }