【发布时间】:2022-01-13 14:08:41
【问题描述】:
处理执行某些操作但条件不同的 if 块的最佳方法是什么?
假设我在 JavaScript 中有这个函数。
const updateText1 = function (id) {
const selector = $(id);
selector.on('change', function () {
const text = selector.val();
if(seen[text]) {
// update some fields here
} else {
//more stuff here
}
})
}
但是我需要在 if 语句中做同样的事情,但使用不同或相似的条件
const updateText2 = function (id) {
const selector = $(id);
selector.on('change', function () {
const text = selector.val();
if(seen[text] || text.trim() === '') {
// update some fields here
} else {
//more stuff here
}
})
}
那么else函数就是这样使用的
obj1 = {
test: function() { updateText1(this.id) }
}
obj2 = {
test: function() { updateText2(this.id) }
}
我知道我可以将逻辑组合在一起,但是,由于这个函数所附加的两个对象处理的事情略有不同,我试图让我的代码保持干燥,而不是多次重复 if 主体。我试过注入这样的逻辑
obj2 = {
// logic code here
test: function() { updateText2(this.id, logic) }
}
但这会导致代码不更新,因为值是通过 jQuery on change 获取的。
我是不是想太多了,我应该只是结合逻辑,还是有更好的方法来组织和处理这个?
【问题讨论】:
-
function (id, checkBlank=false)及更高版本,if(seen[text] || (checkBlank && text.trim() === '')) ...
标签: javascript oop design-patterns functional-programming