Extend behavior while honoring the base contract
extends links a derived class to a base class. A derived constructor calls super before using this, so the base instance state is initialized. A method can override an inherited method and call the base implementation through super.method().
class Lesson {
constructor(title) { this.title = title; }
describe() { return 'Lesson: ' + this.title; }
}
class TimedLesson extends Lesson {
constructor(title, minutes) {
super(title);
if (!Number.isFinite(minutes) || minutes <= 0) {
throw new RangeError('Duration must be positive');
}
this.minutes = minutes;
}
describe() {
return super.describe() + ' (' + this.minutes + ' min)';
}
}
const lesson = new TimedLesson('Closures', 20);
console.log(lesson.describe()); // Lesson: Closures (20 min)
console.log(lesson instanceof Lesson); // trueInitialization order
The base constructor handles base initialization. The derived constructor adds its own rules afterward. Accessing this before super in a derived constructor is an error. If you omit a derived constructor, JavaScript provides default forwarding behavior suitable for the ordinary case.
Private fields are not protected fields
A base class's #private fields cannot be directly named by derived-class code. Expose a deliberate method or getter when a subclass needs a supported operation. Do not assume inheritance grants access to all implementation details.
Use inheritance selectively
TimedLesson is still a Lesson with extra timing information. A Course containing many lessons is usually a composition relationship, not “Course extends Array” merely to reuse list methods. Keep subclasses substitutable: an override should not silently break assumptions made by callers of the base interface.
Practice
- Add VideoLesson with a URL field and an overridden description.
- Pass several lesson types to a function that calls describe.
- Test zero, negative and NaN durations.
- Explain why calling super.describe preserves the base message while adding detail.
हिन्दी संकेत: inheritance का अर्थ valid base behavior को आगे बढ़ाना है; केवल code reuse के लिए हर relationship को extends न बनाएं।