instead of conditional call  [ 721 views ]

I want to create an easy adjustable command processor class with some implemented callable commands.
The command definition like this:

...
myClass.prototype.commandFirst = function(uID){
  ... do something ...
  return true;
};
myClass.prototype.commandSecond = function(uID){
  ... do something ...
  return true;
};
...

In a conditional world we can do the following:

myClass.prototype.commandReceived = function(cmd){
  var x = cmd.command, uID = x.u, vCmd = x.cmd, ret = false;
  
  // simple conditional way
  if (vCmd == 'commandFirst'){ ret = this.commandFirst(uID); }
  else if (vCmd == 'commandSecond '){ ret = this.commandSecond(uID); }
  // !!! of course we need to edit this section all time
  // !!! when we want to extend the class with a new command 
  else { console.log('unimplemented command: ' + vCmd); }

  return ret;
};

Be careful we need to edit this statement every time when we want to put new command into the collection.
So we can avoid this if we can release the old method…
Instead of this long way use the tricky way based on the javascript soul:

myClass.prototype.commandReceived = function(cmd){
  var x = cmd.command, uID = x.u, vCmd = x.cmd, ret = false;

  // Tricky call here.
  this[vCmd] ? (ret = this[vCmd](uID)) : console.log('unimplemented: ' + vCmd);

  return ret;
};

This is because

myClass.prototype.commandSecond callable as myClass['commandSecond']

#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }