I would like to know if I'm doing it properly...
Having this code:
class Room {
constructor(type, size, hasWindows, equipment) {
this.type = type;
this.size = size;
this.hasWindows = hasWindows;
this.equipment = ['esterillas', ...equipment];
};
};
class PilatesRoom extends Room {
};
const room1 = new PilatesRoom('pilates', 20, true, ['balón medicinal'])
console.log(room1);
//returns: PilatesRoom {type: "pilates", size: 20, hasWindows: true, equipment: Array(2)}
I mean... I don't really need to use "constructor" and "super" to make it works perfectly, but when I check it on the internet, everybody uses it. Should I? For example:
class PilatesRoom extends Room {
constructor(type, size, hasWindows, equipment) {
super(type, size, hasWindows, equipment)
};
};
This returns the same.
I'm trying to understand! Thank you guys for your time.
You don't have to add a child class constructor if it doesn't add any logic. (In fact, static analysis and code quality tools sometimes flag it as a "useless constructor" and give a warning.)
Some programmers prefer the explicit definition of the constructor, some may carry over habits from other languages which may require it, etc. But unless the child constructor is actually doing something for the child class other than just passing the same values to the parent constructor, it's not necessary.
You have to use the super() expession when you want to use a constructor of your child class. Otherwise you don't have to. As simple as that.
class PilatesRoom extends Room {
// the constructor should be removed (there is no point to keep it):
constructor(type, size, hasWindows, equipment) {
super(type, size, hasWindows, equipment)
};
};
In the above code, there is no reason to define a constructor. However in the below code you have to call foo() and thus, you also have to use super():
class PilatesRoom extends Room {
constructor(type, size, hasWindows, equipment) {
super(type, size, hasWindows, equipment)
foo()
};
};
More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super#Description
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With