I am trying to figure out if there is a better practice for initializing class members of derived classes in ES6 - in the child or the parent, and why?
For example:
Option 1:
class AbstractAnimal {
constructor() {
this.voice = null;
}
makeVoice() {
this.voice.make();
}
}
class Dog extends AbstractAnimal {
constructor() {
super();
this.voice = new Bark();
}
onSeeFriend() {
this.makeVoice();
}
}
Option 2:
class AbstractAnimal {
constructor(voice) {
this.voice = voice;
}
makeVoice() {
this.voice.make();
}
}
class Dog extends AbstractAnimal {
constructor() {
super(new Bark());
}
onSeeFriend() {
this.makeVoice();
}
}
Obviously, there are pro's and cons in both methods. The first options spreads the initialization of members around, which makes it harder to trace. While the second option will bubble everything up to one place, but than you could end up with huge constructors taking a lot of arguments.
Would appreciate it if I could hear your thought about this. Thanks!