Problem Statement
What does the super keyword do in a class?
Explanation
The super keyword is used to call functions on an object's parent class.
In a constructor, super calls the parent constructor and must be called before accessing this.
In methods, super accesses parent class methods.
You must call super in the child constructor before using this, or you will get an error.
Super provides clean syntax for inheritance compared to older patterns.
It is essential for extending classes in ES6.
Code Solution
SolutionRead Only
// Parent class
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(this.name + ' is eating');
}
makeSound() {
console.log('Some generic sound');
}
}
// Child class
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}
bark() {
console.log(this.name + ' says woof!');
}
makeSound() {
super.makeSound(); // Call parent method
console.log('Woof woof!');
}
}
const buddy = new Dog('Buddy', 'Golden Retriever');
buddy.eat(); // 'Buddy is eating' (inherited)
buddy.bark(); // 'Buddy says woof!' (own method)
buddy.makeSound();
// 'Some generic sound'
// 'Woof woof!'
// Must call super before this
class Cat extends Animal {
constructor(name, color) {
// this.color = color; // ReferenceError!
super(name); // Must call super first
this.color = color; // Now this is ok
}
}
// Static methods and super
class Parent {
static info() {
console.log('Parent info');
}
}
class Child extends Parent {
static info() {
super.info(); // Call parent static method
console.log('Child info');
}
}
Child.info();
// 'Parent info'
// 'Child info'
// Prototype chain with classes
const dog = new Dog('Max', 'Labrador');
// dog -> Dog.prototype -> Animal.prototype -> Object.prototype -> null
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(dog instanceof Object); // true