The Prototype Pattern in JavaScript, With Real Examples
The prototype pattern creates objects by copying an existing one. See Object.create, structuredClone and class cloning in JavaScript, with deep copy pitfalls.

The prototype pattern creates new objects by copying an existing one, the prototype, instead of building each from scratch. It pays off when construction is expensive or when you want many variations of a configured object. JavaScript is unusual because it is prototype-based at its core: every object has a prototype link, Object.create() makes an object that inherits from another, and the class keyword is syntax over the same chain. That gives the word "prototype" two meanings that are easy to confuse: the design pattern of cloning, and the language mechanism of inheritance. This post covers both, on Node.js 24: Object.create, shallow copies, deep copies with structuredClone, cloning class instances and the traps with shared references, functions and private fields. Every sample prints its output.
Two meanings of prototype
In the language, Object.create(proto) returns a new object whose prototype is proto. Property lookups that miss on the object continue to the prototype.
const baseTask = {
priority: "normal",
describe() {
return `${this.title} (${this.priority})`;
},
};
const task = Object.create(baseTask);
task.title = "Write report";
console.log(task.describe());
console.log(Object.keys(task));
console.log(Object.getPrototypeOf(task) === baseTask);Write report (normal)
[ 'title' ]
truetask has one own property, title. priority and describe come from the prototype by delegation, not by copying. That is the language feature. The design pattern is different: it creates an independent copy, so changes to the clone do not touch the original.
Clone with a shallow copy
For flat data the spread operator and Object.assign copy own enumerable properties.
const template = { type: "invoice", currency: "USD", tags: ["draft"] };
const a = { ...template, number: 1 };
const b = { ...template, number: 2 };
console.log(a, b);
a.currency = "EUR";
console.log(template.currency);{ type: 'invoice', currency: 'USD', tags: [ 'draft' ], number: 1 } { type: 'invoice', currency: 'USD', tags: [ 'draft' ], number: 2 }
USDChanging a.currency left the template alone, since strings are copied by value. Now the trap: the spread copy is shallow, so nested objects and arrays are shared.
const template = { type: "invoice", tags: ["draft"] };
const a = { ...template };
const b = { ...template };
a.tags.push("urgent");
console.log(b.tags);
console.log(template.tags);[ 'draft', 'urgent' ]
[ 'draft', 'urgent' ]All three objects point at one tags array. Pushing through a changed b and the template. This is the most common bug with this pattern in JavaScript, and it comes from confusing a shallow copy with a clone.
Deep clone with structuredClone
structuredClone() is built into Node.js 17 and later and into modern browsers. It copies nested data by value and handles cycles, Date, Map, Set, RegExp, typed arrays and more.
const template = {
type: "invoice",
tags: ["draft"],
issued: new Date("2026-11-20T00:00:00Z"),
lines: new Map([["A1", { qty: 1 }]]),
};
const copy = structuredClone(template);
copy.tags.push("urgent");
copy.lines.get("A1").qty = 5;
console.log(template.tags, template.lines.get("A1").qty);
console.log(copy.tags, copy.lines.get("A1").qty);
console.log(copy.issued instanceof Date, copy.issued === template.issued);[ 'draft' ] 1
[ 'draft', 'urgent' ] 5
true falseThe copy is independent in every level, and dates and maps keep their types. Before structuredClone, many people used JSON.parse(JSON.stringify(x)), which turns dates into strings and silently drops undefined, functions, Map and Set. Prefer structuredClone for data.
const original = { when: new Date("2026-11-20T00:00:00Z"), skip: undefined, nested: new Set([1]) };
const viaJson = JSON.parse(JSON.stringify(original));
console.log(viaJson);{ when: '2026-11-20T00:00:00.000Z', nested: {} }The date became a string, skip vanished and the Set became an empty object.
What structuredClone cannot copy
It does not clone functions, and it throws on them, and it does not preserve class identity: a class instance comes back as a plain object with the same own data properties, without its prototype.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
norm() {
return Math.hypot(this.x, this.y);
}
}
const p = new Point(3, 4);
const clone = structuredClone(p);
console.log(clone, clone instanceof Point, typeof clone.norm);
try {
structuredClone({ run() {} });
} catch (err) {
console.log(err.name, "-", err.message);
}{ x: 3, y: 4 } false undefined
DataCloneError - run() {} could not be cloned.The clone lost its methods because they live on Point.prototype, and structuredClone does not carry the prototype. Functions in data throw DataCloneError. So for objects with behavior, you need a clone method of your own.
A clone method on a class
The pattern as the catalog describes it gives the object a clone() that knows how to copy itself correctly.
class Report {
#createdBy;
constructor({ title, sections = [], createdBy }) {
this.title = title;
this.sections = sections;
this.#createdBy = createdBy;
}
clone(overrides = {}) {
return new Report({
title: this.title,
sections: this.sections.map((s) => ({ ...s })),
createdBy: this.#createdBy,
...overrides,
});
}
summary() {
return `${this.title} by ${this.#createdBy}: ${this.sections.length} sections`;
}
}
const monthly = new Report({
title: "Monthly report",
sections: [{ heading: "Revenue" }, { heading: "Costs" }],
createdBy: "finance",
});
const november = monthly.clone({ title: "November report" });
november.sections.push({ heading: "Notes" });
console.log(monthly.summary());
console.log(november.summary());
console.log(november instanceof Report);Monthly report by finance: 2 sections
November report by finance: 3 sections
trueclone passes through the constructor, so private fields such as #createdBy are set correctly, which structuredClone and spread cannot do, since private fields are not copied by either. The new report copies each section object, so adding a section to the clone leaves the original at two. The overrides parameter turns the clone into a "copy with changes", which is the most useful form in practice: start from a configured template, change two fields.
Prototype as a registry of templates
The classic use is a registry of ready-made prototypes that you clone to create instances.
const templates = {
welcome: { subject: "Welcome", body: "Thanks for signing up", footer: ["unsubscribe"] },
receipt: { subject: "Your receipt", body: "Thanks for your order", footer: ["unsubscribe", "help"] },
};
function fromTemplate(name, overrides = {}) {
const template = templates[name];
if (!template) throw new Error(`No template: ${name}`);
return { ...structuredClone(template), ...overrides };
}
const email = fromTemplate("receipt", { to: "[email protected]" });
email.footer.push("returns");
console.log(email);
console.log(templates.receipt.footer);{
subject: 'Your receipt',
body: 'Thanks for your order',
footer: [ 'unsubscribe', 'help', 'returns' ],
to: '[email protected]'
}
[ 'unsubscribe', 'help' ]Each call yields an independent object seeded from the template, and the template stays pristine. This is the same idea as test data factories, which clone a base fixture and tweak fields.
Prototypal inheritance in practice
The language-level prototype matters for performance and design. Methods defined on a class live once on the prototype and are shared by all instances, while arrow-function properties assigned in a constructor are created per instance.
class A {
say() {
return "a";
}
}
class B {
say = () => "b";
}
const [a1, a2] = [new A(), new A()];
const [b1, b2] = [new B(), new B()];
console.log(a1.say === a2.say, b1.say === b2.say);true falseAll A instances share one say, and each B has its own copy. For thousands of instances the shared version uses less memory, which is the mechanism, and you should not infer any specific timing from it. Use per-instance arrow functions when you need a bound this, such as a callback, and prototype methods otherwise.
Pitfalls
Shallow copies share nested data, as shown. Know which level your copy reaches.
**
Object.create(null)** makes a prototype-less object, handy as a dictionary since keys liketoStringdo not collide, but it has nohasOwnPropertyand prints differently.Prototype pollution. Merging untrusted JSON into an object with a naive recursive copy can write to
Object.prototypethrough a__proto__key, affecting every object in the process. Never use a hand-rolled deep merge on untrusted input without blocking__proto__,constructorandprototype, or usestructuredCloneand an allowlist of keys.Mutating built-in prototypes, such as adding a method to
Array.prototype, affects all code and can break libraries.
Where the advice stops
Do not clone when constructing is cheap and a factory is clearer. Do not deep-copy large structures on every request when immutable updates would share most of the data. If your data is plain, structuredClone is the tool, and if it has behavior, write clone() on the class. Reserve Object.create for the rare cases where delegation, not copying, is what you want.
Copy-on-write as an alternative
Cloning everything up front is wasteful when most of the data stays the same. A common alternative is to share structure and copy only the parts that change, which is how immutable updates work. Instead of cloning a large state tree, create a new object that reuses the untouched branches.
const state = { user: { name: "Ada" }, settings: { theme: "dark", locale: "en" }, cart: { items: [1, 2, 3] } };
const next = { ...state, settings: { ...state.settings, theme: "light" } };
console.log(next.settings.theme, state.settings.theme);
console.log(next.user === state.user, next.cart === state.cart, next.settings === state.settings);light dark
true true falseOnly settings was copied, and user and cart are shared between the old and new states. Because nothing mutates them, sharing is safe, and it is cheap regardless of how large those branches are. Libraries such as Immer automate this with a draft you mutate normally. If you find yourself deep-cloning large objects on every change, switch to this style and reserve structuredClone for the cases that need real isolation, such as handing data to a worker or storing a snapshot.


