[英]How to refactor a JavaScript function that is used twice
我有這兩個條件
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.