Reputation: 73
I am new to JS and was learning classes and the inheritance but I faced the confusion of why to use the super method in child class. Here is the code:
class Animal {
constructor(name, weight) {
this.name = name;
this.weight = weight;
}
eat() {
return `${this.name} is eating!`;
}
sleep() {
return `${this.name} is going to sleep!`;
}
wakeUp() {
return `${this.name} is waking up!`;
}
}
class Gorilla extends Animal {
constructor(name, weight) {
super(name, weight);
}
climbTrees() {
return `${this.name} is climbing trees!`;
}
poundChest() {
return `${this.name} is pounding its chest!`;
}
showVigour() {
return `${super.eat()} ${this.poundChest()}`;
}
dailyRoutine() {
return `${super.wakeUp()} ${this.poundChest()} ${super.eat()} ${super.sleep()}`;
}
}
console.log((new Gorilla("Jonas", 12)).dailyRoutine());
As you can see the gorilla class uses super method and if I remove that super method I get an error but WHY? I just cannot when to use super method and why?
Upvotes: 1
Views: 66
Reputation: 138257
super()
inside the constructor allows you to pass arguments to the parent constructor.
class Parent {
constructor(weNeedThis) {
console.log(weNeedThis);
}
}
const parent = new Parent("When constructing, it's easy to pass the argument");
class Child {
constructor() {
// But how do we pass an argument to the parent's constructor here?
}
}
So in other words, we need super()
sometimes to pass arguments to the parent constructor.
if I remove that super method I get an error but WHY?
That's for consistency. If some constructors would call super()
and others wouldn't, it is unclear when and how the parents constructor runs. Therefore it is specified, that if you provide your own constructor
, you have to call super
before you can access this
. When super()
gets called, the parent constructor gets run with the arguments provided, this
gets initialized and is accessible from then on.
Upvotes: 1
Reputation: 12805
super
gives you access to the parent class. In your specific example, you need to call the Animal
constructor and provide the parameters that needs. The reason that it throws the error without it is that the Animal
portion of your object can't be initialized without running through the constructor.
super
will also give you reference to the other functions and properties within the parent class.
Check out the official documentation to get more information.
Upvotes: 1
Reputation: 1926
The call to super()
initializes the super
, or parent, class. The parent class and it's members must be initialized first, as the child class usually depends on them to some extent. You cannot inherit a class and not initialize the parent because you may not be able to access members that the child class depends on.
Upvotes: 2