ES6 **extends** implements prototype-based inheritance cleanly. The child class must call **super()** in its constructor before accessing `this`. Calling `super.method()` invokes the parent's method. Under the hood, this sets up the prototype chain so child instances have access to parent prototype methods.
1Understanding Inheritance
ES6 extends implements prototype-based inheritance cleanly. The child class must call super() in its constructor before accessing this. Calling super.method() invokes the parent's method. Under the hood, this sets up the prototype chain so child instances have access to parent prototype methods.
Always call super() before using 'this' in a subclass constructor — it's required, or you get a ReferenceError.
class Shape {
constructor(color) { this.color = color; }
describe() { return `A ${this.color} shape`; }
}
class Circle extends Shape {
constructor(color, radius) {
super(color); // must be first!
this.radius = radius;
}
area() { return Math.PI * this.radius ** 2; }
describe() { return `${super.describe()} (circle r=${this.radius})`; }
}
const c = new Circle('red', 5);
console.log(c.describe());
console.log(c.area().toFixed(2));2Practical Example
Here is a real-world application of Inheritance showing how it is used in production JavaScript code.
// instanceof checks prototype chain
console.log(c instanceof Circle); // true
console.log(c instanceof Shape); // true
console.log(c instanceof Object); // true3Best Practices
Follow these guidelines when working with Inheritance:
1. Use extends for is-a relationships
2. Prefer composition over inheritance for has-a relationships
3. Call super() first in subclass constructors
Tip: Always call super() before using 'this' in a subclass constructor — it's required, or you get a ReferenceError.
class Shape {
constructor(color) { this.color = color; }
describe() { return `A ${this.color} shape`; }
}
class Circle extends Shape {
constructor(color, radius) {
super(color); // must be first!
this.radius = radius;
}
area() { return Math.PI * this.radius ** 2; }
describe() { return `${super.describe()} (circle r=${this.radius})`; }
}
const c = new Circle('red', 5);
console.log(c.describe());
console.log(c.area().toFixed(2));