Create new objects by copying an existing instance (the prototype). Object creation is expensive or complex. You need many similar instances with
Prototype
Overview
Create new objects by copying an existing instance (the prototype).
When to use
- Object creation is expensive or complex.
- You need many similar instances with small variations.
Java example
TypeScript example
Pros and cons
Pros:
- Fast creation via cloning.
- Avoids complex constructor logic.
Cons:
- Deep copy can be tricky.
- Clones may share mutable state if not careful.
Common pitfalls
- Shallow copy of nested objects.
- Mutating shared references after cloning.