Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
JS

JavaScript

The language of the web, on the client, the server and the edge.

Paradigm
Multi-paradigm, prototype-based, functional
Typing
Dynamic, weak (TypeScript adds static types)
Memory
Garbage collected
Runs
V8 / SpiderMonkey / JSC engines (JIT)
Concurrency
Single-threaded event loop, workers
Behavioral pattern

Memento

Intent

Saves and restores an object's previous state without revealing its implementation.

Problem

An editor needs undo, but snapshotting requires access to private fields.

Solution

The originator produces snapshot objects itself; a caretaker stores them.

Real-world analogy

Think of it like this

Saving your game before the boss fight, so you can reload if things go wrong.

Structure

association / extends implements / depends on
Originator - state+ save(): Memento+ restore(m: Memento) 1 Memento - state+ getState() 2 Caretaker - originator- history: Memento[]+ doSomething()+ undo() 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Originator — Originator produces snapshots of its own state and restores from them.
  2. 2Memento — Memento is an immutable snapshot of the originator's state.
  3. 3Caretaker — Caretaker knows when to capture and restore, and keeps a history stack.

Code example

A JavaScript code sample for Memento is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Memento when undo / snapshots.

Use Memento when direct access to fields would break encapsulation.

Pros and cons

Pros

  • Snapshots without breaking encapsulation

Cons

  • Memory use with frequent snapshots

Relations with other patterns

Check yourself

Check yourself

A form editor must restore its previous state when the user presses Cancel.

Saved in this browser only. Part of Behavioral patterns (0/11).