我有这两个条件
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/