gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:28:51 25 4
gpt4 key购买 nike

我有这两个条件

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com