简体   繁体   中英

How to use Mixins for every type of inheritance?

I've recently saw the concept of Mixin in javascript mainly through the article Real Mixins with javascript classes . And as I understand is a way to do multiple inheritance with abstract classes and it is more like a composition than an inheritance. I'm also reading about the concept composition over inheritance, as in the article Composition Over Inheritance . I'm aware that the discussion about inheritance and composition can be very long, but I've chosen to avoid inheritance as much as I can (at least for now).

So I would like to use Mixins as much as I can with ES6 and in most of examples I see three classes in action like class A extends MixinB(C) . What if I want to extend only the class B? Would I do something like class A extends MixinB(Object) ? This might be an anti pattern as the Mozilla documentation states.

Note that I could do a direct inheritance like class A extends B , but like this B is not a Mixin anymore and I would need a different declaration of B if I would like to use it as a Mixin.

I think that a solution for what you are looking for it would be to change the definition of Mixin functions.

Instead of having:

MixinB(WhateverClass)

You could have:

Mixin(MainClass, otherClass1, otherClass2...)

Where this would be true:

MixinB(C) = Mixin(B, C)

I didn't like the sound of this!

So I would like to use Mixins as much as I can

Use mixins where appropriate, not because you want to use them. Inheritance is appropriate for fixed, strong relationships. Mixins are useful when you have a small piece of functionality you want to share with a number of classes that are not related otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM