[英]Constructor and class properties within javascript mixins
I am trying understand mixins in javascript and all the examples and articles i have read so far talk about adding methods and not properties. 我正在尝试理解javascript中的mixin,以及到目前为止我已阅读的所有示例和文章都在谈论添加方法而不是属性。
I have found Alex Jover Morales' article really useful and i have slightly modified his example to include an additional mixin and constructors with new properties within the mixins here . 我发现Alex Jover Morales的文章非常有用,并且我对他的示例进行了一些修改,以在此处的 mixin中包含其他mixin和具有新属性的构造函数。
Is what i have done below an anti-pattern? 我在反模式下做了什么? Is there a problem with having a constructor and properties within a mixin?
在mixin中包含构造函数和属性是否存在问题? Is there a problem with calling super() within each mixin's contructor?
在每个mixin的构造函数中调用super()是否存在问题?
const PlayMixin = superclass => class extends superclass { constructor(args) { let { favouriteGame } = args super(args); this.favouriteGame=favouriteGame; } play() { console.log(`${this.name} is playing ${this.favouriteGame}`); } }; const FoodMixin = superclass => class extends superclass { constructor(args) { let { genericFood } = args super(args); this.genericFood=genericFood; } eat() { console.log(`${this.name} is eating ${this.genericFood}`); } poop() { console.log("Going to 💩"); } }; class Animal { constructor(args) { let {name} = args this.name = name } } class Dog extends PlayMixin(FoodMixin(Animal)) { constructor(...args) { super(...args) } bark() { console.log("Woff woff!") } haveLunch() { this.eat(); this.poop(); } } const jack = new Dog({name:"Jack", genericFood:"lobster", favouriteGame:"chess"}); jack.haveLunch(); jack.play();
.as-console-wrapper { max-height: 100%!important; top: 0; }
Is what i have done below an anti-pattern?
我在反模式下做了什么?
No, it is not. 不它不是。
Is there a problem with having a constructor and properties within a mixin?
在mixin中包含构造函数和属性是否存在问题?
No, as long as you call super(...)
in a manner that it works for all mixed in classes. 不,只要您以对所有混合类都有效的方式调用
super(...)
。
Is there a problem with calling super() within each mixin's contructor?
在每个mixin的构造函数中调用super()是否存在问题?
No, super
always points to the extended class, there isno problem in calling that constructor. 不,
super
始终指向扩展类,调用该构造函数没有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.