Constructor Parameters and super()
You'll learn: How to pass arguments from a child class constructor through super() to initialize the parent class with specific values.
When a child class needs a constructor, it must call super() before accessing this. But what if your parent class constructor expects parameters? You pass them directly through super().
The Core Idea
Think of super() as a phone call to your parent class's constructor. If the parent needs information (parameters) to set itself up, you "forward" those values through the super() call.
Here's the pattern:
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age); // Pass name and age to Animal
this.breed = breed; // Add Dog-specific property
}
}
const buddy = new Dog('Buddy', 5, 'Golden Retriever');
console.log(buddy.name); // 'Buddy'
console.log(buddy.age); // 5
console.log(buddy.breed); // 'Golden Retriever'
The Dog constructor receives three parameters but only uses two of them for the parent. It forwards name and age to Animal via super(name, age), then handles its own breed property.
Why This Matters
Child classes often need additional properties beyond what the parent handles. By accepting parameters and routing the relevant ones to super(), you maintain clean separation: the parent initializes shared properties, while the child adds specialized ones.
Key Takeaway: Pass arguments to super() just like calling any function—it routes those values to the parent constructor, allowing the child to accept both inherited and new parameters.