我有这两个条件

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 }
  })


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

最佳答案

您可以提取如下函数:

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);
    }

关于javascript - 如何重构两次使用的JavaScript函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43583346/

10-11 05:37