I need to define a function that can be used by multiple classes, but as far as I understand, inheriting from a superclass doesn’t work for me. Essentially, what I would like to achieve is the ability to extend multiple interfaces for each class.
For example, if I have defined classes Apple
, Orange
, Banana
, I want all of them to have an identical isFresh()
function. I also like to let Apple
, Orange
, and Earth
to have a getRadius()
method. This is somewhat similar to Apple interface Fruit, SphericalObject {...}
I also want to be able to override the functions if I want to. However, inheritence doesn’t work for me because I would like to inherit from multiple superclasses.
What is the best way to achieve this?
I am aware of this similar post, I understand from that JavaScript is dynamically typed and does not have interfaces, and the suggested Duck Type doesn’t seem to solve my problem. I don’t really care to check if the method in interface exist in child classes.
3
Answers
Looks like you’re looking for "mixins". They are not built-in in javascript, but are quite easy to implement in userland, for example:
You only needs a single
extends
to achieve your result.On the risk of being misprised extensively: inspired by Douglas Crockford I stopped using classes or prototypes (well, classes I never used in ES, never had any use for it).
Instead I create factory functions. Here’s an examplary Fruit factory.
To play with the idea I created a small Stackblitz project, with a more generic approach.