mercredi 14 octobre 2015

Advantages of treating function as an object

Recently I came across a simple Command pattern implementation in JavaScript that uses function as an object instead of pure object to define functionality:

var CommandManager = (function() {
  function CommandManager() {}

  CommandManager.executed = [];
  CommandManager.unexecuted = [];

  CommandManager.execute = function execute(cmd) {
    cmd.execute();
    CommandManager.executed.push(cmd);
  };

  CommandManager.undo = function undo() {
    var cmd1 = CommandManager.executed.pop();
    if (cmd1 !== undefined){
      if (cmd1.unexecute !== undefined){
        cmd1.unexecute();
      }
      CommandManager.unexecuted.push(cmd1);
    }
  };

  CommandManager.redo = function redo() {
    var cmd2 = CommandManager.unexecuted.pop();

    if (cmd2 === undefined){
      cmd2 = CommandManager.executed.pop();
      CommandManager.executed.push(cmd2); 
      CommandManager.executed.push(cmd2); 
    }

    if (cmd2 !== undefined){
      cmd2.execute();
      CommandManager.executed.push(cmd2); 
    }
  };

  return CommandManager;
})(); 

and the usage:

CommandManager.execute({
  execute: function(){
    // do something
  },
  unexecute: function(){
    // undo something
  }
});

//call unexecute of prev. command
CommandManager.undo(); 
//call execute of prev. command
CommandManager.redo(); 

My question would be, is there any advantages in defining CommandManager function this way, instead of directly defining properties on object literal and assigning it back to var CommandManager

Aucun commentaire:

Enregistrer un commentaire