【问题标题】:Javascript - lots of standalone functions are bad ??? (node.js)Javascript - 很多独立功能不好??? (node.js)
【发布时间】:2018-11-27 07:25:23
【问题描述】:

我现在正在重构我的代码..我必须重构我的大量 if..else 语句,所以我现在要根据每个条件创建许多函数。

代码:

class Strategy {
    constructor(state) {
        this.state = state;

        if(this.state === 1){
          return first();
        }else if (val === 2){
          return second();
        }else if (val === 3){
          return third();
        }
    }

}

function first(){
  //do something
}

function second(){
  //do something
}

function third(){
  //do something
}

let firstClass = new Strategy(1);

每个函数都可以按条件声明??? 或者,在原型方法中声明每个函数更好吗?/?

【问题讨论】:

  • 欢迎来到 StackOverflow。我不认为constructor() 意味着返回任何东西。您只需使用它来初始化一个实例。但除非函数在其他地方共享,否则最好将它们作为匿名函数内联包含
  • 更好的方法是原型化你的函数并使用 switch case 来执行函数。
  • 谢谢大家

标签: javascript node.js if-statement design-patterns refactoring


【解决方案1】:

你也可以使用普通的 JS 对象作为策略图,像这样:

const strategies = {
    1: () => {},  //do something
    2: () => {},   //do something
    3: () => {}   //do something
}

你可以像这样使用它:

strategies[state]();

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2021-08-05
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多