Pattern 14/22 · Creational

Prototype

Create new objects by copying an existing template object instead of rebuilding an expensive configuration from scratch — and in JS/TS, the hard part isn't "cloning" but cloning *correctly*: shallow or deep, and whether the prototype, Maps/Sets, and circular references survive.

Creational●●○14 min read8 stepsalso known as: Clone, Copy
clonedeep copyshallow copystructuredClonestatesnapshotcreational

01 — It starts with code that is breaking

Problem

You're building a landing page editor. The user clicks "Create block from template", and the template is a 40-field config object: layout, padding, animation, a list of breakpoints, a list of child blocks. You write the line everyone writes: const block = { ...template }, change the title, change the padding, done.

A week later there's a bug: changing the new block's padding also changes the padding of the original template. Every block created after that in the session inherits the broken padding. The reason: spread only copies one level. block.style and template.style are still the same object, so block.style.padding = 24 writes into the shared object. In production, that config gets saved to the DB and turns into 300 broken pages.

You "fix" it with JSON.parse(JSON.stringify(template)). It works, and it silently breaks three things: Date becomes a string, Map/Set become {}, every function (including class methods) evaporates, and undefined keys get dropped. The UI receives an object that "looks like" the template: typeof block.publishedAt === "string" so .getTime() blows up; or instanceof BlockConfig === false so block.getLabel() is undefined halfway through. TypeScript says nothing, because JSON.parse returns any.

Then come circular references. Your tree node has a parent pointing back up to its parent, a perfectly normal structure. JSON.stringify(node) throws "Converting circular structure to JSON", and the natural reflex is... to drop the parent pointer so JSON works — turning a graph into a tree, after which a few other modules start rebuilding the parent-child relationship by hand, each in its own way.

The problem grows with the project: every feature invents its own way to copy ({...o}, lodash cloneDeep, JSON round-trip, Vue's toRaw() followed by a hand-rolled clone). Nobody decides once how this object gets copied. The result: the same template, copied in three places at three different depths, and the bug comes back every time someone adds a nested field.

02 — The idea, before touching code

Solution

Prototype says: let the object know how to copy itself. Instead of outsiders guessing its internal structure and copying by hand, the class itself declares a clone() method — it knows which fields are primitives, which need a new object, and which are shared resources that must not be copied (connections, handles, DOM nodes).

In TS/JS, clone() rarely needs a complicated algorithm; what it really buys you is one single, named place to decide deep versus shallow. A named decision can be reviewed, tested, and fixed once. By contrast, {...x} scattered across 40 call sites is 40 implicit decisions, and every new nested field is another potential bug.

Pick the tool based on what the object contains: all primitives and flat fields, spread is enough, don't second-guess it. A plain data tree, structuredClone() — a real deep copy that handles circular references and keeps Date/Map/Set/ArrayBuffer, but loses functions and loses the prototype. Class instances with methods need a hand-written clone() (calling the constructor with copied data), or controlled serialization (a schema + zod, superjson). Prototype doesn't force you to pick one of the three — it forces you to choose deliberately, and choose right on the class.

03 — Doing it for real, one code fragment per step

Step by step

1

Find the right target: what is expensive to rebuild

Prototype isn't for 3-field objects created with new. It's for objects whose "original" accumulates the result of an expensive process: reading from the DB, parsing a config file, building a breakpoint tree, deriving defaults from a theme, or a designer hand-configuring 40 parameters.

How to spot it in code: a createDefault...() / getTemplate...() function gets called and then mutated right away at the call site. That mutation point is exactly where you need clone(), because the template is a shared asset.

tsblock-service.ts
const template = await loadBlockTemplate('hero-v3') // 12 DB queries + parse

const block = template
block.style.padding = 24        // <- editing the template directly!
block.title = 'Holiday Sale'

await save(block)
It works without a copy... until a second block is created from the same template.
Key pointIf the template object takes 100ms to build and 0ms to copy, Prototype is almost certainly the right choice.
2

Be explicit: copy, or "set up again from scratch"

There are two ways to get an identical object: rerun the whole initialization (loadBlockTemplate() again), or copy the existing object. The first is independent of the template's current state — if the config was just edited by the user in memory, you lose that.

When the template lives in a cache/in memory and you need a copy of that exact version, only copying will do. When the template comes from a pure, deterministic, cheap function: calling the function again is enough and more honest. Don't write a clone() that calls load() again inside — that's Factory Method in disguise, and it's slower than cloning.

tstwo-ways.ts
// A. Rebuild: safe, but drops the template's current state
const block1 = await loadBlockTemplate('hero-v3')

// B. Copy from the object living in memory: keeps every modification
const block2 = block.clone()
Key pointPrototype copies what exists; if you copy by rerunning initialization, you're using the wrong pattern.
3

Shallow copy: spread and Object.assign only go one level deep

{...o}, Object.assign({}, o), with structuredClone nowhere in sight: both spread-style copies only create a new object at the outermost level. Every reference value (object, array, Map, Date, function) has its pointer copied.

The trap is that it's right 90% of the time, and the other 10% is data corruption with no exception. Rule of thumb: spread is only safe when the object is flat.

tsshallow.ts
const template = { id: 'hero-v3', tags: ['hero'], style: { pad: 8 } }

const a = { ...template }        // spread
const b = Object.assign({}, template)
const c = structuredClone(template) // deep, for comparison

a.tags.push('a'); a.style.pad = 99
b.style.pad = 42

console.log(template.tags.join('+'), template.style.pad)
console.log(c.tags.join('+'), c.style.pad)
console
hero+a 42
hero 8
Both are "copies", at two different depths. Line 1: the template is already corrupted. Line 2: structuredClone didn't touch the original.
Key pointSpread doesn't "make a copy"; it makes a new object that shares all its contents with the old one.
4

JSON round-trip: the convenient trap

JSON.parse(JSON.stringify(x)) is a deep copy... provided your object only contains things JSON can describe. It destroys selectively: Map/Set → {}, function → skipped, undefined → key dropped, Date → ISO string, BigInt → throws, and a graph with cycles → throws "Converting circular structure to JSON".

Worst of all, the consequences don't show up immediately: the returned object still "looks right", so it slips through the UI, then blows up 3 calls later, or doesn't blow up and saves a wrong value to the DB. And since JSON.parse returns any, TypeScript stays out of it.

tsjson-trap.ts
class BlockConfig {
  constructor(public title: string, public at: Date, public meta: Map<string, number>) {}
  label() { return this.title + ' @ ' + this.at.toISOString() }
}

const orig = new BlockConfig('hero', new Date(0), new Map([['v', 3]]))
const copy: any = JSON.parse(JSON.stringify(orig))

console.log('at:', typeof copy.at, '| meta:', JSON.stringify(copy.meta))
console.log('label:', typeof copy.label, '| instanceof:', copy instanceof BlockConfig)

const node: any = { name: 'root', children: [] }
node.children.push(node)
try { JSON.stringify(node) }
catch (e) { console.log('circular ->', (e as Error).name) }
console
at: string | meta: {}
label: undefined | instanceof: false
circular -> TypeError
All three "disappearances" (Date to string, Map to {}, methods gone) are silent. Only the circular one complains.
Key pointIf the object has a Date, Map, Set, BigInt, function, or class instance: JSON round-trip isn't a deep copy, it's data loss.
5

structuredClone: a proper deep copy, but not for classes

structuredClone() (Node 17+, Bun, modern browsers, globalThis) uses the structured clone algorithm — the same algorithm postMessage uses to send data to a Worker. It's deep, it handles circular references while preserving relationships (two pointers to the same object still point to one shared object after cloning), and it keeps Date, Map, Set, RegExp, ArrayBuffer, Error.

The price: it works from an allowlist of types, not from the prototype. Function → DataCloneError. Proxy → DataCloneError (Vue's reactive()/ref() objects, MobX stores, Vitest mocks are all Proxies). Class instances get cloned into plain objects: the data survives, instanceof and methods don't.

tsstructured-clone.ts
const tree: any = { name: 'root', children: [] }
tree.parent = null
tree.children.push(tree)

const cloned = structuredClone(tree)
console.log('deep:', cloned.children[0] === cloned)     // cycle preserved
console.log('isolated:', cloned.children[0].children === tree.children)

const reactiveLike = new Proxy({ a: 1 }, {})
try { structuredClone(reactiveLike) }
catch (e) { console.log('proxy ->', (e as Error).name) }

class K { constructor(public n = 1) {} m() { return 'm' } }
const ck: any = structuredClone(new K())
console.log('class ->', ck instanceof K, typeof ck.m, JSON.stringify(ck))
console
deep: true
isolated: false
proxy -> DataCloneError
class -> false undefined {"n":1}
The graph is preserved, the Proxy is rejected, the class is "flattened" into data. Three behaviors, three different design decisions.
Key pointstructuredClone copies data, not behavior. Does your object have methods? If so, it doesn't belong to structuredClone.
6

Let the object clone itself: this is the real Prototype

Now back to GoF: a clone() interface, and each class implements it. In TS, interface Cloneable<T> is enough. clone() calls the constructor (no hand-copying the prototype), so the result is always an instance of the right type, instanceof holds, and methods are intact.

The crux is in the body of clone(): you explicitly list which fields get a new object and which keep the same reference. This is where the "how deep" decision gets written down once, with a name, under code review, instead of being silently re-decided at every call site.

tsblock-config.ts
interface Cloneable<T> { clone(): T }

class BlockConfig implements Cloneable<BlockConfig> {
  constructor(
    readonly title: string,
    readonly tags: string[],
    readonly style: { pad: number, bg: string },
    readonly publishedAt: Date,
    readonly meta: Map<string, number>,
  ) {}

  label() { return this.title + ' [' + this.tags.join('+') + ']' }

  clone(): BlockConfig {
    return new BlockConfig(
      this.title,
      [...this.tags],                        // array: make a new one
      { ...this.style },                     // flat object: shallow is enough
      new Date(this.publishedAt.getTime()),  // Date: make a new one
      new Map(this.meta),                    // Map: copy constructor
    )
  }
}

const a = new BlockConfig('hero', ['hero'], { pad: 8, bg: '#fff' }, new Date(0), new Map([['v', 1]]))
const b = a.clone()
b.tags.push('sale'); b.style.pad = 24; b.meta.set('v', 2)

console.log(a.label(), a.style.pad, a.meta.get('v'))
console.log(b.label(), b.style.pad, b.meta.get('v'))
console.log('right type:', b instanceof BlockConfig)
console
hero [hero] 8 1
hero [hero+sale] 24 2
right type: true
Key pointThe body of clone() is the object's blueprint: it says which fields it owns and which it references. Read those 15 lines and you understand the semantics of the whole class.
7

Cloning a graph with back-references: you need a memo Map

Tree nodes with a parent, graphs with two-way edges, lists of items pointing at one shared object. A naive deep copy of the "clone() calls each child's clone()" kind will loop forever — or, more subtly, bloat: the same child object gets cloned twice into two separate copies, and a.children[0].owner === b.owner becomes false.

The antidote: a memo Map<object, object> that lives for the duration of one clone. "Has this original object been copied already? If so, return the existing copy." This is exactly how structuredClone keeps a graph consistent.

tsgraph-clone.ts
function deepClone<T>(root: T): T {
  const seen = new Map<unknown, unknown>()
  const copy = (n: any): any => {
    if (n === null || typeof n !== 'object') return n
    const hit = seen.get(n)
    if (hit) return hit                    // already copied -> reuse, keep relationships
    if (Array.isArray(n)) {
      const arr: any[] = []
      seen.set(n, arr)                     // register BEFORE recursing
      arr.push(...n.map(copy))
      return arr
    }
    const out: any = {}
    seen.set(n, out)                       // register BEFORE recursing
    for (const k of Object.keys(n)) out[k] = copy(n[k])
    return out
  }
  return copy(root) as T
}

const sharedTheme = { primary: '#f60' }   // SHARED object, owned by no node
const root: any = { name: 'root', theme: sharedTheme, parent: null, children: [] }
const child: any = { name: 'child', theme: sharedTheme, parent: root, children: [root] }
root.children.push(child)

const c = deepClone(root)
console.log('cycle   :', c.children[0].children[0] === c)
console.log('parent  :', c.children[0].parent === c)
console.log('identity:', c.theme === c.children[0].theme, '| detached from original:', c.theme !== sharedTheme)
console
cycle   : true
parent  : true
identity: true | detached from original: true
Calling seen.set before recursing is the make-or-break detail: do it after and the cycle overflows the stack. And the shared object is cloned only ONCE, so the sharing relationship stays intact.
Key pointCopying an object means copying data. Copying a graph means copying data and relationships. No memo, no relationships.
8

Enforce it with types, then test it for real once

Require every object used as a template to declare clone() via the Cloneable<T> interface. That way there's nowhere left calling JSON.parse(JSON.stringify(x)) on an object that "might have methods": you can't clone something that hasn't declared how it gets cloned.

And test with exactly the thing that will break: change a nested field of the clone and assert the original didn't change. Add a new nested field and forget to update clone(), and this test catches it immediately — that's the whole value of the pattern, locked in by 6 lines of test.

tsclone.test.ts
interface Cloneable<T> { clone(): T }

class BlockConfig implements Cloneable<BlockConfig> {
  constructor(
    readonly title: string,
    readonly tags: string[],
    readonly style: { pad: number, bg: string },
    readonly publishedAt: Date,
    readonly meta: Map<string, number>,
  ) {}

  clone(): BlockConfig {
    return new BlockConfig(
      this.title, [...this.tags], { ...this.style },
      new Date(this.publishedAt.getTime()), new Map(this.meta),
    )
  }
}

const original = new BlockConfig('hero', ['hero'], { pad: 8, bg: '#fff' }, new Date(0), new Map([['v', 1]]))
const draft = original.clone()

draft.style.pad = 24          // must only affect the draft
draft.tags.push('sale')
draft.meta.set('v', 9)

console.log('original after editing draft:', original.style.pad, original.tags.join('+'), original.meta.get('v'))

// Guard: anything used as a template MUST declare how it gets cloned
function asTemplate(x: Cloneable<unknown>): void { void x }
asTemplate(original)
console
original after editing draft: 8 hero 1
This test is the regression net for exactly the class of bug that opened this page: editing a clone that leaks into the original.
Key pointWithout a "edit the clone, the original stays the same" test, clone() is just a nice name for a bug that hasn't arrived yet.

04 — Who talks to whom

Structure

  • PrototypeThe self-copy contract: `clone(): this`. In TS usually `interface Cloneable<T>`.
  • ConcretePrototypeA concrete class that implements `clone()` by calling its own constructor with data copied to the right depth.
  • ClientNeeds an object like the template. Just calls `template.clone()`, without knowing how many nested fields the template has.
  • PrototypeStoreHolds prebuilt templates, looked up by key: template, preset, plan tier, theme. Combines with a registry/factory.
  • ClonerThe copy strategy (spread, structuredClone, schema-based serialization, graph clone with memo). Chosen by the object's contents, kept in one place.
   Client
     │  template.clone()
     ▼
┌───────────────────────────┐     ┌─────────────────────────┐
│ Prototype (Cloneable<T>)  │ ◄───│ PrototypeStore          │
│  + clone(): T             │     │  'hero-v3' → template   │
└─────────────┬─────────────┘     │  'card'    → template   │
              │ implement         └─────────────────────────┘
              ▼
┌───────────────────────────────────────────────┐
│ ConcretePrototype (BlockConfig)               │
│  + clone() ──► new BlockConfig(               │
│                  [...tags], { ...style },      │
│                  new Date(at), new Map(meta))  │
│  decides HOW DEEP, here, once                 │
└───────────────┬───────────────────────────────┘
                │ used when needed
       ┌────────┴─────────┐
       ▼                  ▼
  1-level spread     structuredClone
  (flat object)      (plain data, cycles ok)
                     ✗ function, ✗ Proxy,
                       ✗ class prototype

05 — Edit freely, run it right here

Try it: four ways to copy, four different results

tsdemo.ts
class Widget {
  constructor(public id: string, public tags: string[], public style: { pad: number }) {}
  label() { return this.id + '/pad=' + this.style.pad }
}
const base = new Widget('base', ['header'], { pad: 8 })

// 1) Shallow: a NEW object, but nested fields still share references
const shallow = { ...base }
shallow.tags.push('sidebar')
shallow.style.pad = 99
console.log('1 shallow    :', base.tags.join('+'), '| base.style.pad =', base.style.pad)

// 2) JSON round-trip: methods gone, prototype chain gone
const plain = JSON.parse(JSON.stringify(base))
console.log('2 json       : label =', typeof plain.label, '| instanceof Widget =', plain instanceof Widget)

const cfg = { cache: new Map([['a', 1]]), hook: () => 1, empty: undefined }
const jsonCfg = JSON.parse(JSON.stringify(cfg))
console.log('3 json lossy : cache =', JSON.stringify(jsonCfg.cache), '| hook =', typeof jsonCfg.hook, '| empty kept =', ('empty' in jsonCfg))

// 3) Circular: JSON throws, structuredClone survives and keeps the graph
const node: any = { name: 'root', children: [] }
node.children.push(node)
try { JSON.stringify(node) }
catch (e) { console.log('4 json throws:', (e as Error).name) }
const clonedNode = structuredClone(node)
console.log('5 clone ok   : self-ref =', clonedNode.children[0].children === clonedNode.children)

// 4) Hand-written clone(): a deep copy that keeps the right class
class CloneableWidget {
  constructor(public id: string, public tags: string[], public style: { pad: number }) {}
  clone(): CloneableWidget { return new CloneableWidget(this.id, [...this.tags], { ...this.style }) }
}
const w = new CloneableWidget('w', ['a'], { pad: 4 })
const w2 = w.clone()
w2.tags.push('b')
console.log('6 clone()    : right class =', w2 instanceof CloneableWidget, '|', w.tags.join('+'), 'vs', w2.tags.join('+'))
console
1 shallow    : header+sidebar | base.style.pad = 99
2 json       : label = undefined | instanceof Widget = false
3 json lossy : cache = {} | hook = undefined | empty kept = false
4 json throws: TypeError
5 clone ok   : self-ref = true
6 clone()    : right class = true | a vs a+b

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • There's a "template" that is expensive to build (many DB queries, parsing, derived defaults) and you need many copies that differ in a few fields. This is the pattern's original use case.
  • Presets / themes / plan tiers / template marketplaces: an approved configuration where the user only edits a small part.
  • You need a snapshot to compare or undo: keep the original in memory and diff it against the edited clone (pairs with Memento).
  • The object has many nested fields and you want to decide copy depth once, on the class, not at every call site.
  • Graphs/trees with back-references or several pointers to the same node: cloning them with correct semantics needs a memo — all the more reason to centralize it in one place.
  • Conversely, a flat object of primitives: {...o} is the right choice, don't add any layers.

Don't use it when

  • Shallow when you needed deep — a real bug, silent, and it spreads to the DB. Spread and Object.assign only change the outermost level; adding one new array/object field is enough for it to come back.
  • JSON.parse(JSON.stringify()) destroys data selectively and reports no errors: Date→string, Map/Set→{}, functions dropped, undefined keys lost, while BigInt and cycles throw. It also returns any, so the type checker can't save you.
  • structuredClone rejects function and Proxy (DataCloneError), and cloning a class instance loses the prototype: the data survives, instanceof is wrong, methods are undefined. Send a store/actions to a Worker via postMessage and you'll hit this right away. If you need to keep behavior, write your own clone().
  • Object.freeze(obj) only freezes the top level; nested fields can still be modified, so "the template is frozen, we're safe" is a false sense of security. Truly freezing it requires recursion, and at that point you should use as const + clone on use.
  • Over-engineering: a 4-field object, no nesting, no cycles. Writing a 40-line clone() for it is inventing cost. Prototype pays off when re-initialization is expensive, or when the object is nested/graph-shaped enough that nobody can copy it correctly by eye.
  • Cloning isn't immutability. Copy-on-write beats clone-then-mutate for large objects: use readonly/as const in the contract and only clone when you actually branch, otherwise you pay for a copy on every read.

07 — You have met it already, just not by name

In real code

DOM: node.cloneNode(deep)

The purest Prototype example in the browser: a node that knows how to copy itself, and the deep parameter is exactly the "how far to copy" question. Note that it does not copy listeners registered with addEventListener and doesn't copy form state — same lesson: cloning the shape isn't cloning the behavior.

postMessage / Web Worker / worker_threads

Passing data between threads uses the structured clone algorithm: deep, keeps Date/Map/ArrayBuffer/cycles, but send a function to a Worker and you get DataCloneError. That's why every Worker API accepts data describing the work (a message), not a callback.

Global structuredClone() (Node 17+, Bun, browser)

A global function, no import, deep-copies plain data. Vue/Nuxt: objects from reactive()/ref() are Proxies, so structuredClone throws DataCloneError — you have to toRaw() first, and if that object has actions it still can't be cloned: you can only clone data, not a store.

Clipboard/drafts in Vue/Nuxt

Saving a form draft and then "Reset to original": the common pattern is to snapshot once (structuredClone(toRaw(form)) or a schema-based clone) and restore from it. Snapshot at the wrong depth = reset only restores top-level fields, and the user sees a form that "didn't fully reset".

Immutable stores (Redux, Pinia, TanStack Query)

Modern stores avoid deep clones with structural sharing: unchanged objects keep their references, and only the path to the changed part is recreated ({...state, user: {...state.user, name}}). If you deep clone the whole state in a selector/reducer, you've just broken reference equality yourself and made the UI re-render the entire tree.

08 — Try it yourself

Exercise

Given `type Node = { name: string, owner: { id: string }, parent: Node | null, children: Node[] }` (the `parent` pointer creates a cycle). a) Write `deepCopyNaive(n)` that copies recursively without a memo, then call it on a tree with 2 nodes pointing at **one** shared owner object; point out what goes wrong. b) Write a correct `cloneTree(n)`: no infinite loop, the shared owner is still **one** object, and `parent` points to a node in the clone rather than the original.

Hints, open them one at a time:

  1. Without a memo the cycle makes the recursion never stop — where do you need to cut it off? Do you call seen.set before or after recursing into the children?
  2. Shared things (owner) and things owned by the node (children) must be handled differently: one is reused via the Map, the other is created fresh.
  3. Once cloned, test with three asserts: c.children[0].parent === c, c.children[0].owner === c.children[1].owner, c.children[0].owner !== original.children[0].owner (if owner is copied) — or === if you deliberately share the owner. Choose, then write the test for that choice.

Two parts: a Map to stop cycles and reuse the copy of a shared object, and the rule "register the copy before recursing". For owner, sharing versus copying is a business decision: if the owner is a shared entity (user, tenant), keep the reference to the original object; if the owner belongs to the node, copy it through the same Map. Don't forget that even a simple nested field (owner: { ...n.owner }) is a decision that needs to be written down.

tsexercise.ts
type Node = { name: string, owner: { id: string }, parent: Node | null, children: Node[] }

// owner is a shared entity: KEEP the reference (don't copy)
function cloneTree(root: Node): Node {
  const seen = new Map<Node, Node>()
  const copy = (n: Node): Node => {
    const hit = seen.get(n)
    if (hit) return hit
    const out: Node = { name: n.name, owner: n.owner, parent: null, children: [] }
    seen.set(n, out)
    out.parent = n.parent ? copy(n.parent) : null
    out.children = n.children.map(copy)
    return out
  }
  return copy(root)
}

const owner = { id: 'u1' }
const root: Node = { name: 'root', owner, parent: null, children: [] }
const a: Node = { name: 'a', owner, parent: root, children: [root] }
const b: Node = { name: 'b', owner, parent: root, children: [] }
root.children.push(a, b)

const c = cloneTree(root)
console.log(c.children[0].parent === c)                      // true
console.log(c.children[0].children[0] === c)                 // cycle, true
console.log(c.children[0].owner === c.children[1].owner)     // shared, true
console.log(c.children[0].owner !== c.children[0].parent)    // no type mix-up, true

09 — Read them in pairs to see the essence

Related patterns

  • Abstract FactorySame creational family: Abstract Factory builds objects from a **recipe**, Prototype builds objects from **a live template**. When the "recipe" is long and mostly defaults, Prototype is cheaper.
  • BuilderBuilder also starts from multi-step configuration, but it produces objects that are *valid by construction order*. Prototype produces objects that are *identical*, even half-finished ones. Template + mutate = Prototype; build step by step + validate = Builder.
  • MementoA Memento **is** a snapshot for restoring — and a snapshot is only trustworthy when copied to the right depth. Prototype is how you take the snapshot, Memento is why you take it (undo, rollback, drafts).
  • CompositeA Composite is a tree of nested nodes; cloning a composite has to recurse and handle parent-child references. This is where shallow copies break fastest.