Prototype: creating by copying

  • Lesson 8 of 32
  • 10 min
  • Intermediate
  • 11 steps

Sometimes the easiest way to create an object is to copy one that is already set up. The pattern is simple; the hard part is knowing what gets copied and what gets shared.

How it is made
clone()
editoreditorgamegameyour codeyour codeeditorpresetpresetgoblingoblinprototemplatepresetcopycopycopytwinobjnew rowcopystylestylestylestylestylestylestyleown styleown styleown styleown styleown styleown styleown styleDB connectionDB connection 2PrototypePrototypePrototypePrototypePrototypePrototypePrototypealready set uprepeats every fieldAnother rectangle, by handconst a = {kind: "rect",x: 10,style: { fill: "crimson" },};copies the presetonly x changesCopy and change+const a = { ...preset, x: 10 };// kind and style come from presetfill = "black"the original changedOne style for bothconst a = { ...preset, x: 10 };+a.style.fill = "black";preset.style.fill; // "black"its own stylestill "crimson"Deep copy+const b = structuredClone(preset);b.style.fill = "black";preset.style.fill; // "crimson"copied too muchmeant to be sharedDecide field by fieldkind, xcopystylecopy deeplyDB connectionshareplain object · no classA class instanceclass Enemy {constructor(hp, pos) { … }}const goblin = new Enemy(100, pos);+const c = structuredClone(goblin);c instanceof Enemy; // falsegoblin.clone()instanceof EnemyThe class knows how to copy itselfclass Enemy implements Prototype {+clone() {+return new Enemy(this.hp,+{ ...this.pos });+}}looks up what it lackswrites to itselfThe JavaScript prototypeconst proto = { kind: "rect" };+const obj = Object.create(proto);obj.kind; // "rect", from protoobj.kind = "circle"; // ownproto.kind; // still "rect"hidden, a mouldno listeners · duplicate idStamping rows from a templateconst row = tpl.cloneNode(true);+row.id = "row-2"; // unique id+row.addEventListener("click", open);list.append(row);do you need a copy?never duplicatedPrototype or not?many variants of one presetcopycreating is cheap and clearconstructor or factorysockets, files, listenersdo not copycopy + what differsWhat each tool copies{...obj}the top levelnested objects are sharedstructuredCloneeverything, cycles toono functions, no classcloneNode(true)node and subtreeno listenersown clone()what you decideyou pick the depth
  • request
  • response
  • replication

Step 1 of 11

Problem

Another one, written from scratch

Your drawing editor has a preset: a rectangle already set up with its kind, position and style. You need another one just like it, but at x: 10.

Building it by hand means repeating every field and knowing how it is put together, and if the preset changes tomorrow, your hand-written copy is out of date.

Step 2 of 11

Concept

The idea: copy the original and change what differs

Prototype offers another way to create: instead of building from scratch, you start from an object that is already set up, copy it and change only what is different.

In JavaScript the shortest way is the spread: { ...preset, x: 10 } creates a new object with the preset fields and overrides x. Whoever copies does not need to know how the original was built.

What changed

  • Copy of the preset
  • Only x changes

Step 3 of 11

Problem

You change the copy and break the original

The spread makes a shallow copy: the top level is new, but style is a nested object and the copy keeps a reference to the same style.

When you run a.style.fill = "black", the preset turns black too: both point at the same object. It is one of the most common bugs with objects in JavaScript.

What changed

  • style is the same object for both
  • The preset changed without you touching it

Step 4 of 11

Solution

A deep copy copies the inside too

structuredClone(preset) makes a deep copy: it creates new objects at every level, so the copy has its own style. It even keeps circular references.

Now b.style.fill = "black" changes only the copy; the preset stays "crimson". It is a global function in browsers and Node, no library needed.

What changed

  • The copy gets its own style
  • The preset does not change

Step 5 of 11

Trade-off

Copying deeply can also copy too much

A deep copy is not always safer. If the preset holds something that must be shared, like a database connection, a naive deep copy would try to duplicate it. The Python copy docs warn about it: a deep copy may copy too much, including data meant to be shared between copies.

The way out is to decide field by field: data gets copied, resources (connections, files, sockets) are shared or created again. Copying deeply also costs more than copying the top level.

Step 6 of 11

Problem

structuredClone does not keep your class

In a game you have a goblin, an instance of the Enemy class. Copy it with structuredClone and you get a plain object: the algorithm does not walk the prototype chain, so c instanceof Enemy is false and its methods are gone.

It does not copy functions either (it throws DataCloneError) or DOM nodes, and it loses getters, setters and property descriptors.

What changed

  • The copy lost the Enemy class

Step 7 of 11

Solution

Let the object know how to copy itself

The classic form of the pattern: a Prototype interface with a clone() method, and each class implements it. Enemy.clone() creates a new Enemy and copies pos into its own object.

Whoever asks for the copy just calls goblin.clone(): it does not need to know the concrete class or how it is built. And the class decides what it copies deeply and what it shares.

What changed

  • Prototype interface with clone()
  • The copy is still an Enemy

Step 8 of 11

Technique

Where you meet it: the JavaScript prototype

JavaScript has this idea built into the language. Object.create(proto) creates a new object whose prototype is proto: whatever the object lacks, it looks up on proto.

Writes go to the new object: obj.kind = "circle" leaves proto alone. JavaScript classes rest on this same mechanism, which is why the name shows up in the docs and in interviews.

What changed

  • obj delegates what it lacks to proto

Step 9 of 11

Technique

Where you meet it: copying DOM nodes

A typical frontend use: a hidden row works as a template and tpl.cloneNode(true) copies it with its whole subtree for each new item.

But listeners you added with addEventListener are not copied, and if the template has an id, the copy repeats it. After cloning, fix the id and add the listeners again.

What changed

  • New row from the template
  • New id and listener by hand

Step 10 of 11

Trade-off

When not to use Prototype

If creating the object is cheap and clear with a constructor or a factory, copying only adds one more question: what is shared?

Do not copy objects that hold resources that must not be duplicated either (sockets, open files, listeners). Prototype shines when you have one well set-up original and many variants of it.

Step 11 of 11

Summary

Create by copying, knowing what you copy

Prototype creates objects by copying one that is already set up and changing what differs; whoever copies does not need to know the class or the recipe.

The hard part is the copy: spread shares nested objects, structuredClone copies data but drops the class, cloneNode does not copy listeners, and your own clone() lets you pick the depth field by field.

You will learn

  • Create objects by copying one that is already set up
  • Why `{...obj}` shares nested objects
  • Choose a shallow or deep copy on purpose
  • When a class needs its own `clone()`
  • Where it shows up in JavaScript and the DOM