The 'not class' pattern

Adam Crockett 🌀 - Nov 7 '19 - - Dev Community

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
});
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .