Prototype
Clone existing objects instead of constructing from scratch β the object knows how to copy itself, keeping internals private.
Intent & Description
π― Intent
Create new objects by copying existing configured ones, without depending on their concrete class or re-running expensive initialization.
π Context
You need to duplicate complex objects β game entities, configured document templates, pre-built UI components β but constructing from scratch is expensive or requires knowing private implementation details. You want to stamp out copies of a ‘prototype’ instance.
π‘ Solution
Add a clone() method to the object. It creates a copy of itself using whatever deep-copy logic is appropriate for its internals. Callers just call clone() β they don’t need to know the class name, constructor parameters, or internal structure.
Real-world Use Case
Source
π TL;DR
Object clones itself via clone(). Skip construction overhead, clone a pre-configured prototype instead. Circular references make deep clone logic gnarly β handle with care.
Advantages
- Clone without coupling to the concrete class β work purely with the interface.
- Skip expensive re-initialization by cloning a pre-configured instance.
Disadvantages
- Deep cloning objects with circular references gets complicated fast.
class Rectangle {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
clone() {
return new Rectangle(this.width, this.height, this.color);
}
}
const original = new Rectangle(10, 20, "blue");
const copy = original.clone();
console.log(copy !== original); // true