ES6 - Where is it better to initialize a member - parent class or derived class?

问题: 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: Op...

问题:

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!


回答1:

As this question is an opinion poll I would just like to point out that there is a third way, as always in JS: Mixins

Pros: allows abstracting the initialisation away to a third class; AbstractAnimal is truly abstract
Cons: can be hard to justify for simple cases such as a barking Dog

class AbstractAnimal {
  makeVoice() { this.voice.make(); }
}
const Barking = Base => class extends Base {
  constructor() {
    super();
    this.voice = new Bark();
  }
}
class Dog extends Barking(AbstractAnimal) {
  onSeeFriend() { this.makeVoice(); }
}


class Bark { make() { console.log('Woof'); } }
new Dog().onSeeFriend();

  • 发表于 2019-03-17 21:45
  • 阅读 ( 163 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除