Using super
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 37 of 56.
When you override a method, you can still access the parent's original version using super.methodName(). This lets you extend or modify parent behavior instead of completely replacing it.
Create a parent class with a method:
class Animal {
makeSound() {
return "Generic animal sound";
}
}Create a child class that extends the parent:
class Dog extends Animal {
makeSound() {
// Call the parent's method first
const parentSound = super.makeSound();
// Then extend with additional functionality
return `${parentSound}, but also Woof!`;
}
}Create an instance of the child class:
const myDog = new Dog();
console.log(myDog.makeSound());
// Output: "Generic animal sound, but also Woof!"The super keyword allows you to call the parent class's methods while still adding your own functionality in the child class.
Challenge
You're given a Shape class with a calculateArea() method and a Rectangle class that extends it. Your task is to override the calculateArea() method in Rectangle using super.
Your task is to complete the calculateArea() method in the Rectangle class to:
- Call the parent's
calculateArea()method usingsuperand store the result - Calculate the rectangle's actual area:
width × height - Return a combined string: parent's message + rectangle area. Example:
Calculating area... Rectangle area: 50
Cheat sheet
Use super.methodName() to access the parent class's original method when overriding:
class Animal {
makeSound() {
return "Generic animal sound";
}
}
class Dog extends Animal {
makeSound() {
const parentSound = super.makeSound();
return `${parentSound}, but also Woof!`;
}
}
const myDog = new Dog();
console.log(myDog.makeSound());
// Output: "Generic animal sound, but also Woof!"This allows you to extend parent functionality instead of completely replacing it.
Try it yourself
import { Shape } from './shapes.js';
import { Rectangle } from './shapes.js';
// Test code - do not modify
const rectangle = new Rectangle(5, 10);
console.log(rectangle.calculateArea()); // Expected: "Calculating area... Rectangle area: 50"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge