When working with JavaScript classes, chances are high that you’ve encountered the mysterious super
keyword. Its purpose remains somewhat unclear until diving deeper into class inheritance scenarios. Put simply, super
offers convenient access to the parent class's logic inside derived classes, ensuring seamless integration between various layers of abstraction.
Before exploring practical uses of super
, let's briefly review its syntax:
// Inside a derived class constructor
super(arguments);
// Invoking parent class methods
super.methodName(arguments);
With the basics covered, let’s dive into an actual example illustrating how super
simplifies class inheritance in real-world situations. Imagine developing a game featuring multiple types of characters sharing similar attributes yet possessing distinct abilities. To achieve this goal, we could apply single inheritance leveraging the super
keyword as shown below:
class Character {
constructor(name, health) {
this.name = name;
this.health = health;
}
introduce() {
console.log(`Hi, I am ${this.name}, and I currently have ${this.health} hit points…