I am coining the term 'not class' because until anyone tells me what this is I am going to refer to it incorrectly otherwise.
The premise is simple, Classes in JavaScript are just a little restrictive, when you go down this route you lose the flexibility of using objects, what if you wanted multiple inheritence or a proxyless new hook and so on. I believe strongly (as an ex class lover) that this pattern is a better way.
I also really like the word new
, so here is the code.
const MemoryCtrl = {
new(config) {
// a new instance of this entire object will be created
// I could change what new does, or even add some extends methods bellow
const inst = Object.create(this)
this.construct(inst, config);
return inst;
},
construct(inst, config) {
inst._memory = new WebAssembly.Memory(config);
inst._mut = new Uint8Array(this._mut);
},
append(...bytes) {
this._mut.findIndex((occupied) => !occupied);
// Some stuff here
},
clear() {
// Some stuff here
},
view() {
console.log(this._mut);
}
}
const mem = MemoryCtrl.new({
initial: 255,
max: 255
});
I could also turn this into a builder patter, or perhaps restrict the amount of methods returned for true privacy, there is a lot of flexibility here.
Anyway, let me know if you like it or hate it and wish I would just use classes and why.
Top comments (6)
I'm not sold on the fact that allowing multiple inheritance is a good thing, but that might be only because I'm currently learning C++.
It is not a good thing. One level max (preferably, composition over inheritance, as classic says), otherwise it becomes nightmare to debug and a huge mental baggage.
I think in my head I have my concepts (names mixed up)
Completely the developers choice to implient, I choose this as an example of flexibility. Anyway I agree multiple inheritance is unpopular perhaps I meant to say composition.
I agree, this is pretty cool - didn't mean to disparage the pattern, this sort of thing had never occurred to me. Re-defining
new
is pretty interesting.Thats alright, I didnt take it that way at all. (im just not feeling well today)