Let's say I have a Thing
class which I want to be both Hideable
and Openable
.
Using a similar approach to Douglas Crockford's object creation through composition, I have been able to "inherit" from multiple classes.
This approach does not work with accessors (getter/setters).
I need to use classes as it's a requirement. I'm also finding that I am duplicating functionality from class to class, but I don't want these to inherit from a base class.
Any ideas?
The progress I have made so far is in the below snippet:
class Openable {
constructor(isOpen = false) {
this._isOpen = isOpen;
}
get isOpen() {
return this._isOpen + ' is stupid.';
}
set isOpen(value) {
this._isOpen = value;
}
}
class Hideable {
constructor(isHidden = false) {
this._isHidden = isHidden;
}
get isHidden() {
return this._isHidden + ' is stupid.';
}
set isHidden(value) {
this._isHidden = value;
}
}
class Thing {
constructor(config) {
let { isOpen, isHidden } = config;
let openable = new Openable(isOpen);
this.isOpen = openable.isOpen;
let hideable = new Hideable(isHidden);
this.isHidden = openable.isHidden;
}
}
let thing = new Thing({
isOpen: true,
isHidden: false
});
Besides that the OP's accessor approach via "pseudo private property" notation and prototypal getters/setters for
Openable
/Hideable
classes already is questionable,trait
s would come closest to the also doubtable requirement of using classes asmixin
surrogates just for the sake of meeting documentation requirements.As long as JavaScript does not provide traits natively, one has to stick to either more advanced
class
based mixin patterns ore one remembers Angus Croll's Flight Mixins.A mixin's
function
body one has to write is close enough to theconstructor
body of aclass
. Nevertheless function based mixins never will be instantiated but always have to be applied to an object/type via eithercall
orapply
.A possible solution, featuring this kind of mixin approach, that already reliably fulfills the OP's requirements then might look like the next provided example code ...
Other answers of mine at SO, that provide similar solutions to related questions, featuring the same approach are ...
Because
isOpen
andisHidden
are accessors, you can't just grab a copy of them, you have to access them when you want them.Still, you can create your own
isOpen
,isHidden
which use the underlying ones:Live example on Babel's REPL
Naturally, if you do this a lot, you'd want to have a worker function to set that up rather than retyping it all the time:
(or do it by grabbing the property descriptor and updating it)
then:
I'd question the requirement that you must use
class
forOpenable
andHideable
. They look much more like mixins to me.