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
Creational pattern

Prototype

Intent

Copies existing objects without making code depend on their classes.

Problem

Copying an object from the outside requires knowing its concrete class and private fields.

Solution

Objects implement a clone method themselves.

Real-world analogy

Think of it like this

Cell division: a cell copies itself. No outside factory needs to know how the cell is built.

Structure

association / extends implements / depends on
Client copy = existing.clone() 4 «interface» Prototype + clone(): Prototype 1 ConcretePrototype - field1+ clone(): Prototype 2 SubclassPrototype - field2+ clone(): Prototype 3

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

  1. 1Prototype — Prototype declares the cloning method.
  2. 2ConcretePrototype — Concrete Prototype implements clone by copying its own fields, including private ones.
  3. 3SubclassPrototype — Subclasses override clone to copy their extra fields too.
  4. 4Client — Client copies any object through the Prototype interface without knowing its class.

Code example

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

Applicability

Use Prototype when code shouldn't depend on concrete classes of objects to copy.

Use Prototype when reducing subclasses that differ only in initialisation.

Pros and cons

Pros

  • Clone without coupling to classes
  • Pre-built prototypes replace repeated setup

Cons

  • Cloning objects with circular references is tricky

Relations with other patterns

Check yourself

Check yourself

Spawning thousands of enemies whose setup is expensive; you want to copy one configured template enemy.

Saved in this browser only. Part of Creational patterns (0/5).