Prototype & Inheritance
JavaScript uses prototypal inheritance where objects can inherit properties and methods from other objects through the prototype chain. Every object has a prototype, and properties are looked up through this chain, enabling powerful inheritance patterns and code reuse.
What is prototypal inheritance in JavaScript?
Every JavaScript object has a hidden link to another object, its prototype. When you read a property the object doesn't have, JavaScript looks up the prototype chain until it finds it or reaches null. That's how arrays get map from Array.prototype and how class inheritance works under the hood.
const animal = { speak() { return "..." } };
const dog = Object.create(animal); // dog's prototype is animal
dog.speak(); // found on the prototype
Object.getPrototypeOf([]) === Array.prototype; // trueLearning Journey
Prototype Basics
Prototype chain, __proto__, constructor
Classical Inheritance
Constructor functions, Object.create
ES6 Classes
Modern syntax, extends, super
Advanced Patterns
Mixins, static methods, getters/setters
Understanding Prototypes
In JavaScript, every object has a hidden property called [[Prototype]] (accessible via __proto__) that points to another object. This creates a chain of objects that JavaScript traverses when looking for properties and methods.
Prototype Chain
Object Instance
The actual object with its own properties
const obj = new Constructor();Constructor.prototype
Shared methods and properties
Constructor.prototype.method = function() {};Object.prototype
Built-in methods like toString(), valueOf()
Key Concepts
Prototype Lookup
JavaScript searches up the prototype chain until it finds the property or reaches null
Shared Methods
Methods on prototype are shared among all instances, saving memory
Dynamic Updates
Changes to prototype affect all instances immediately
Own Properties
Instance properties shadow prototype properties with the same name
Prototype vs __proto__
prototype is a property of constructor functions, while __proto__is a property of object instances that points to the constructor's prototype.
Constructor Function Inheritance
1. Basic Constructor Pattern
Constructor functions create objects and set up their prototype relationships.
function Animal(name, species) {
this.name = name;
this.species = species;
}
// Add methods to prototype (shared by all instances)
Animal.prototype.speak = function() {
return this.name + " makes a sound";
};
Animal.prototype.getInfo = function() {
return this.name + " is a " + this.species;
};
const cat = new Animal("Whiskers", "cat");
const dog = new Animal("Buddy", "dog");
console.log(cat.speak()); // "Whiskers makes a sound"
console.log(dog.getInfo()); // "Buddy is a dog"Methods on the prototype are shared among all instances, making memory usage efficient.
2. Setting up Inheritance
Create inheritance hierarchies using Object.create() and constructor calls.
function Dog(name, breed) {
// Call parent constructor
Animal.call(this, name, "dog");
this.breed = breed;
}
// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// Add Dog-specific methods
Dog.prototype.bark = function() {
return this.name + " barks: Woof!";
};
// Override parent method
Dog.prototype.speak = function() {
return this.bark();
};
const goldenRetriever = new Dog("Max", "Golden Retriever");
console.log(goldenRetriever.speak()); // "Max barks: Woof!"
console.log(goldenRetriever.getInfo()); // "Max is a dog" (inherited)Key Steps
- • Call parent constructor with .call()
- • Use Object.create() for prototype chain
- • Reset constructor reference
- • Add child-specific methods
Benefits
- • Method inheritance and override
- • Proper instanceof relationships
- • Memory-efficient shared methods
- • Extensible class hierarchies
3. Multiple Inheritance Levels
Create deep inheritance hierarchies with multiple levels of parent-child relationships.
function WorkingDog(name, breed, job) {
Dog.call(this, name, breed);
this.job = job;
}
// Inherit from Dog
WorkingDog.prototype = Object.create(Dog.prototype);
WorkingDog.prototype.constructor = WorkingDog;
WorkingDog.prototype.work = function() {
return this.name + " is working as a " + this.job;
};
WorkingDog.prototype.getInfo = function() {
return Dog.prototype.getInfo.call(this) + " (Job: " + this.job + ")";
};
const policeDog = new WorkingDog("Rex", "German Shepherd", "Police K9");
// Has access to all levels of inheritance
console.log(policeDog.speak()); // From Dog
console.log(policeDog.getInfo()); // Overridden in WorkingDog
console.log(policeDog.work()); // Own methodUse ParentClass.prototype.method.call(this) to call parent methods explicitly.
ES6 Classes (Modern Syntax)
1. Basic Class Syntax
ES6 classes provide a cleaner, more familiar syntax for creating constructor functions and inheritance.
class Vehicle {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.isRunning = false;
}
start() {
this.isRunning = true;
return `${this.make} ${this.model} started`;
}
stop() {
this.isRunning = false;
return `${this.make} ${this.model} stopped`;
}
getAge() {
return new Date().getFullYear() - this.year;
}
getInfo() {
return `${this.year} ${this.make} ${this.model}`;
}
}
const car = new Vehicle("Honda", "Civic", 2020);
console.log(car.start()); // "Honda Civic started"
console.log(car.getAge()); // Current year - 2020Note: Classes are syntactic sugar over prototype-based inheritance. They create the same prototype relationships under the hood.
2. Class Inheritance with extends
Use the extends keyword and super() for clean inheritance.
class ElectricVehicle extends Vehicle {
constructor(make, model, year, batteryCapacity) {
super(make, model, year); // Call parent constructor
this.batteryCapacity = batteryCapacity;
this.currentCharge = 100;
}
charge() {
this.currentCharge = 100;
return `${this.make} ${this.model} fully charged`;
}
drive(distance) {
const chargeUsed = distance * 0.3; // 0.3% per mile
this.currentCharge = Math.max(0, this.currentCharge - chargeUsed);
return `Drove ${distance} miles, ${this.currentCharge.toFixed(1)}% charge remaining`;
}
// Override parent method
getInfo() {
return super.getInfo() + ` (Electric, ${this.batteryCapacity}kWh)`;
}
}
const tesla = new ElectricVehicle("Tesla", "Model 3", 2022, 75);
console.log(tesla.start()); // Inherited method
console.log(tesla.drive(50)); // Own method
console.log(tesla.getInfo()); // Overridden methodsuper() Usage
- • In constructor: calls parent constructor
- • In methods: calls parent method
- • Must be called before using 'this'
- • Can pass arguments to parent
Advantages
- • Cleaner, more readable syntax
- • Built-in super() functionality
- • Better IDE support and tooling
- • Familiar to developers from other languages
3. Static Methods and Properties
Static members belong to the class itself, not to instances.
class MathUtils {
static PI = 3.14159265359;
static E = 2.71828182846;
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
static circleArea(radius) {
return this.PI * radius * radius;
}
static distance(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}
}
// Called on the class, not on instances
console.log(MathUtils.add(5, 3)); // 8
console.log(MathUtils.circleArea(5)); // ~78.54
console.log(MathUtils.distance(0, 0, 3, 4)); // 5Static methods are often used for utility functions, factory methods, or class-level operations.
Advanced Patterns
1. Getters and Setters
Control access to object properties with computed properties and validation.
class Circle {
constructor(radius) {
this._radius = radius;
}
get radius() {
return this._radius;
}
set radius(value) {
if (value <= 0) {
throw new Error("Radius must be positive");
}
this._radius = value;
}
get area() {
return Math.PI * this._radius * this._radius;
}
get circumference() {
return 2 * Math.PI * this._radius;
}
get diameter() {
return 2 * this._radius;
}
set diameter(value) {
this.radius = value / 2;
}
}
const circle = new Circle(5);
console.log(circle.area); // ~78.54
circle.diameter = 20; // Sets radius to 10
console.log(circle.radius); // 102. Mixins Pattern
Add multiple capabilities to classes without traditional inheritance.
// Mixin objects
const Flyable = {
fly() {
return `${this.name} is flying at ${this.altitude || 1000} feet`;
},
land() {
this.altitude = 0;
return `${this.name} has landed`;
}
};
const Swimmable = {
swim() {
return `${this.name} is swimming at ${this.depth || 5} feet depth`;
},
surface() {
this.depth = 0;
return `${this.name} surfaced`;
}
};
// Base class
class Bird {
constructor(name) {
this.name = name;
}
eat() {
return `${this.name} is eating`;
}
}
// Apply mixins
Object.assign(Bird.prototype, Flyable);
class Duck extends Bird {
constructor(name) {
super(name);
}
quack() {
return `${this.name} says quack!`;
}
}
// Apply swimming capability to Duck
Object.assign(Duck.prototype, Swimmable);
const duck = new Duck("Donald");
console.log(duck.fly()); // From Flyable mixin
console.log(duck.swim()); // From Swimmable mixin
console.log(duck.quack()); // Own methodMixin Benefits
Mixins allow multiple inheritance-like behavior, code reuse across unrelated classes, and composition over inheritance patterns.
3. Factory Pattern with Classes
Use static methods to create specialized instances or handle complex object creation.
class Shape {
constructor(type) {
this.type = type;
}
static createRectangle(width, height) {
const rect = new Shape("rectangle");
rect.width = width;
rect.height = height;
rect.area = () => width * height;
rect.perimeter = () => 2 * (width + height);
return rect;
}
static createCircle(radius) {
const circle = new Shape("circle");
circle.radius = radius;
circle.area = () => Math.PI * radius * radius;
circle.perimeter = () => 2 * Math.PI * radius;
return circle;
}
static createTriangle(base, height, side1, side2) {
const triangle = new Shape("triangle");
triangle.base = base;
triangle.height = height;
triangle.area = () => 0.5 * base * height;
triangle.perimeter = () => base + side1 + side2;
return triangle;
}
describe() {
return `This is a ${this.type} with area ${this.area()}`;
}
}
const rect = Shape.createRectangle(5, 3);
const circle = Shape.createCircle(4);
console.log(rect.describe()); // "This is a rectangle with area 15"
console.log(circle.describe()); // "This is a circle with area ~50.27"Common Pitfalls & Best Practices
Common Mistakes
Forgetting 'new' keyword
// WRONG
const obj = MyConstructor();
// CORRECT
const obj = new MyConstructor();Incorrect Prototype Setup
// WRONG
Child.prototype = Parent.prototype;
// CORRECT
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;Missing super() call
// WRONG
class Child extends Parent {
constructor(value) {
this.value = value; // Error!
}
}
// CORRECT
class Child extends Parent {
constructor(value) {
super(); // Must call super first
this.value = value;
}
}Best Practices
Use ES6 Classes
Prefer ES6 class syntax for cleaner, more maintainable code. Use constructor functions only when necessary for compatibility.
Favor Composition
Consider composition and mixins over deep inheritance hierarchies. Keep inheritance chains shallow when possible.
Use instanceof and hasOwnProperty
Check object types with instanceof and distinguish own properties from inherited ones with hasOwnProperty().
Document Your APIs
Clearly document which methods are meant to be overridden, which are private, and the expected behavior of inheritance.
Essential Prototype & Inheritance Examples
Code Editor
<pre id="out"></pre>Preview
Key Learning Points:
- • Basic prototype setup with constructor functions
- • Prototype chain exploration and property lookup
- • Constructor function inheritance with Object.create
- • Multiple inheritance levels and method overriding
- • ES6 classes with extends and super
- • Static methods, getters/setters, and mixins
Prototype and inheritance — step by step
The prototype chain — property lookup
Every JavaScript object has an internal [[Prototype]] link. When you access a property, JS first checks the object itself. If not found, it walks up the chain to the prototype, then that prototype's prototype, until it reaches Object.prototype (whose [[Prototype]] is null). This chain traversal is how method sharing works without copying.
🎯 Quick Check
When you define a method on a constructor's .prototype, how many copies of that method exist for 1000 instances?
Prototypes and Inheritance: summary
Key points
- Methods are stored once on the prototype and shared by every instance, which saves memory.
classandextendsare a cleaner syntax for the same prototype mechanism.- Use
Object.hasOwn(obj, key)to check whether a property belongs to the object itself. - Never modify built-in prototypes like
Array.prototypein your own code.
Frequently asked questions
›What is the difference between __proto__ and prototype?
prototype is a property of constructor functions that becomes the prototype of instances created with new. __proto__ (better: Object.getPrototypeOf) is an object's actual link to its prototype.