【发布时间】:2018-11-27 02:45:38
【问题描述】:
我正在尝试重构 if..else 语句。
我的代码:
let condition = 'hi';
if(condition === 'hi'){
commonFunction('hi');
console.log('hi is called');
}else if(condition === 'bye'){
commonFunction('bye');
console.log('bye is called');
}else if(condition.includes('happy')){
commonFunction('happy');
console.log('happy is called');
}else if(condition === 'greeting'){
commonFunction('greeting');
console.log('greeting is called');
}
重构代码:
if(condition === 'hi'){
hi();
}else if(condition === 'bye'){
bye();
}else if(condition.includes('happy')){
happy();
}else if(condition === 'greeting'){
greeting();
}
function hi(){
commonFunction('hi');
console.log('hi is called');
}
function bye(){
commonFunction('bye');
console.log('bye is called');
}
function happy(){
commonFunction('happy');
console.log('happy is called');
}
function greeting(){
commonFunction('greeting');
console.log('greeting is called');
}
像我重构的代码那样按条件声明每个函数更好吗???
或者,创建类并通过构造函数调用 commonFunction 怎么样? (我认为 switch..case 没有用,因为我有一个包含 includes() 的条件)
【问题讨论】:
-
@lucumt 我的情况有 includes() 所以我想我不能使用 switch
-
这实际上与您的函数的动态程度有关。在您的示例中,您可以只声明 1 个函数并传递 2 个参数。您也可以通过字符串调用函数:stackoverflow.com/a/1144334/10412708
-
在上述情况下,我们不能像下面那样做吗? const functionToCall = condtion.includes('hello') ? '你好' : 条件;组件(函数调用);
标签: javascript if-statement design-patterns refactoring conditional-statements