lundi 26 novembre 2018

Javascript - Change lots of if statements by using class (ES6)

I am using lots of if statements in my code now, so I want to change by using class (ES6)

However, I am not much good at Javascript... so PLZ HELP ME..!

Prior code:

//example code
function first(){
  console.log('first scenario called');
}

function second(){
  console.log('second scenario called');
}

function third(){
  console.log('third scenario called');
}

state = 1;
if(state === 1){
  first();
}else if(state === 2){
  second();
}else if(state === 3){
  third();
}
//first scenario called

Changed code:

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(){
  console.log('first scenario called');
}

function second(){
  console.log('second scenario called');
}

function third(){
  console.log('third scenario called');
}

let firstClass = new Strategy(1);
//first scenario called

This is my sample code..

Actually, I have almost 50+ if statments. Is it right way to change lots of if statements???

Aucun commentaire:

Enregistrer un commentaire