JavaScript•Inheritance
JavaScript Class Inheritance with extends and super()
Class inheritance establishes prototype chains, allowing subclasses to reuse and override parent behavior.
Syntax
class SubClass extends BaseClass {
constructor(args) {
super(args);
}
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| extends | Keyword | Designates parent class to inherit from. |
| super() | Call | Calls parent constructor and passes initial arguments. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// Class Inheritance in JavaScript
class Employee {
constructor(name, department) {
this.name = name;
this.department = department;
}
getDetails() {
return this.name + " (" + this.department + ")";
}
}
class Developer extends Employee {
constructor(name, programmingLanguage) {
super(name, "Engineering"); // Call parent constructor
this.programmingLanguage = programmingLanguage;
}
// Method overriding
getDetails() {
return super.getDetails() + " - Specialist: " + this.programmingLanguage;
}
}
const dev = new Developer("Sarah", "TypeScript");
console.log(dev.getDetails());Expected Output:
Sarah (Engineering) - Specialist: TypeScript
How It Works: Step-by-Step
- Line 11: Developer inherits properties and methods from Employee via extends.
- Line 13: super(name, "Engineering") initializes parent constructor state.
- Lines 18-20: Overrides getDetails() while delegating base string to super.getDetails().
Key Concepts
- In derived classes, super() must be called before using this in constructor.
- super.methodName() invokes the parent class implementation of an overridden method.
- instanceof operator checks inheritance across prototype chains.
Common Mistake: Accessing this before calling super() in derived class constructor
In derived class constructors, this is uninitialized until super() has executed.
❌ Incorrect
class Child extends Parent {
constructor(x) {
this.x = x; // ReferenceError: Must call super constructor!
super();
}
}✅ Correct
class Child extends Parent {
constructor(x) {
super();
this.x = x;
}
}Related JavaScript Tutorials & Compiler
JavaScript Classes (ES6): Constructors, Methods & Private Fields
Learn Object-Oriented Programming in JavaScript with class syntax, constructor, and private #fields.
JavaScript Functions: Arrow Functions, Parameters, and Rest
Master function declarations, expressions, arrow functions, and rest parameters (...args).
JavaScript Exception Handling: try, catch, finally & throw
Handle runtime exceptions gracefully without crashing using try, catch, finally, and custom Error objects.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.