Inheritance
Overview
extends creates a class that starts with everything another class has, then adds or changes things. The original is called the parent (or superclass, base class); the new one is the child (or subclass).
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, ${this.name}`;
}
}
class Teacher extends User {
constructor(name, subject) {
super(name); // run User's constructor first
this.subject = subject;
}
greet() {
return `${super.greet()}! I teach ${this.subject}.`;
}
}
new Teacher('Meera', 'JavaScript').greet();
// 'Hi, Meera! I teach JavaScript.'Inheritance lets you put shared behaviour in one place: every kind of user gets greet (and anything else in User) without copying it.
How it works
extends simply links prototypes together. A teacher’s prototype is Teacher.prototype, whose prototype is User.prototype. Method lookups walk up that chain and use the first match they find.
super
- In the constructor,
super(...)calls the parent constructor. You must call it before touchingthis. - In a method,
super.method()calls the parent’s version — handy when you want to extend behaviour rather than replace it.
Forgetting super in a child constructor is a common error:
class Admin extends User {
constructor(name) {
this.level = 'full'; // ReferenceError: Must call super constructor before accessing 'this'
}
}If the child doesn’t need a constructor of its own, leave it out — JavaScript automatically passes all arguments to the parent:
class Student extends User {
enrol(course) {
return `${this.name} enrolled in ${course}`;
}
}
new Student('Ravi').enrol('SQL'); // 'Ravi enrolled in SQL'Overriding methods
Defining a method with the same name as the parent’s overrides it for the child’s instances. You can:
- replace the behaviour completely — just don’t call
super; - extend it — call
super.method()and add to the result, asTeacher.greetdoes.
The parent class is unaffected: plain users still get the original greet.
Polymorphism
Because every subclass has a greet method, code can call greet on a mixed list without knowing which kind each item is:
const people = [new User('Asha'), new Teacher('Meera', 'JS'), new Student('Ravi')];
for (const p of people) {
console.log(p.greet()); // each uses its own version
}This idea — many types, one interface — is called polymorphism.
Checking the family
const t = new Teacher('Meera', 'JS');
t instanceof Teacher; // true
t instanceof User; // true
t instanceof Student; // false
t.constructor.name; // 'Teacher'Extending built-in classes
You can extend JavaScript’s own classes. This is very common with Error (see Custom errors):
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}Composition over inheritance
Deep class trees get hard to change. If Teacher extends User, and HeadTeacher extends Teacher, and OnlineHeadTeacher extends HeadTeacher… a change at the top ripples everywhere, and some combinations don’t fit the tree at all (what about an online student?).
Often it’s simpler to give an object the pieces it needs:
const canLog = (obj) => ({ ...obj, log: () => console.log(obj.name) });Or to have an object contain helpers rather than be one:
class Course {
constructor(title, storage) {
this.title = title;
this.storage = storage; // has-a storage, rather than is-a storage
}
save() {
this.storage.save(this.title);
}
}A good test: use
extendsonly when “a Teacher is a User” is true in every situation. If it’s really “has a” or “can do”, use composition.
Keep hierarchies shallow — one or two levels is plenty for most programs.
Extend a class
Create VideoLesson that extends Lesson, adds a duration field, and overrides summary() to include it, reusing the parent’s version with super.
class Lesson {
constructor(title) {
this.title = title;
}
summary() {
return this.title;
}
}
// write VideoLesson here
new VideoLesson('Closures', 12).summary(); // 'Closures (12 min video)'class VideoLesson extends Lesson {
constructor(title, duration) {
super(title);
this.duration = duration;
}
summary() {
return `${super.summary()} (${this.duration} min video)`;
}
}Summary
extendsmakes a class inherit another class’s methods and fields.- Call
super(...)in the constructor before usingthis. - Override a method by defining it again; call the parent’s with
super.method(). - An instance is
instanceofits own class and every ancestor. - Prefer small hierarchies; composition is often simpler.