Memento

In the Command section, we talked briefly about the ability to undo operations. Creating reversible commands is not always possible. For many operations, there is no apparent reversing operation that can restore the original state. For instance, imagine the code that squares a number:

var SquareCommand = (function () {
  function SquareCommand(numberToSquare) {
    this.numberToSquare = numberToSquare;
  }
  SquareCommand.prototype.Execute = function () {
    this.numberToSquare *= this.numberToSquare;
  };
  return SquareCommand;
})();

Giving this code, -9 will result in 81 but giving it 9 will also result in 81. There is no way to reverse this command without additional information.

The memento pattern provides an approach to restore the state of objects ...

Get Mastering JavaScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.