The Prototype Pattern
You'll learn how to create new objects by cloning existing prototypes, using JavaScript's built-in prototypal inheritance system for efficient object creation.
What Is the Prototype Pattern?
The Prototype Pattern uses an existing object as a blueprint (or "prototype") to create new objects. Instead of constructing objects from scratch each time, you clone a prototype and customize the copy. This is deeply aligned with how JavaScript itself works—every object can delegate to a prototype.
Think of it like using a template document: rather than writing a new contract from scratch, you copy an existing template and just fill in the specific details.
Creating Objects from Prototypes
You can use Object.create() to create a new object that inherits from a prototype:
const carPrototype = {
wheels: 4,
start() {
console.log(`${this.model} is starting`);
}
};
const myCar = Object.create(carPrototype);
myCar.model = 'Tesla';
myCar.start(); // "Tesla is starting"
The new object myCar inherits wheels and start() from carPrototype, but has its own model property.
When to Use This Pattern
The Prototype Pattern shines when:
- You need many similar objects with shared behavior
- Object initialization is expensive or complex
- You want to avoid class hierarchies but still share functionality
const defaultConfig = {
timeout: 3000,
retries: 3,
log() {
console.log(`Timeout: ${this.timeout}ms`);
}
};
const apiConfig = Object.create(defaultConfig);
apiConfig.timeout = 5000; // Override just what you need
Key Takeaway: The Prototype Pattern leverages JavaScript's prototypal inheritance to efficiently create objects by cloning and customizing existing prototypes, reducing duplication and promoting shared behavior.