0

I have a question about a behaviour I want to automate each time I extend a class resulting in a way to know how many classes separate the last iteration of inheritance with the very first class.

So basically the behaviour I want to replicate is this one.

class Zero {
  static count = 0;
  
  get count(){
    return this.constructor.count;
  }
}

class One1 extends Zero{
  static count = super.count +1; //I would love to automate this line so I just have to call it once in the parent constructor or in this constructor so I only would have to call super in the child's constructor
}

class One2 extends Zero{
  static count = super.count +1;
}

class Two extends One1{
  static count = super.count +1;
}

let one1 = new One1();
let one2 = new One2();
let two = new Two();

one1.count // return 1
one2.count // return 1
two.count // return 2

Thank you in advance!

Quentin
  • 11
  • 1

1 Answers1

0

Testing the prototype chain up until the Function prototype can solve this.

class Zero {
  static get count() {
    let count = 0,
      obj = this;
    while (Object.getPrototypeOf(obj) != Function.prototype) {
      count++;
      obj = Object.getPrototypeOf(obj);
    }
    return count;
  }
  get count() {
    let count = 0,
      obj = this.constructor;
    while (Object.getPrototypeOf(obj) != Function.prototype) {
      count++;
      obj = Object.getPrototypeOf(obj);
    }
    return count;
  }

}
class One extends Zero {}
class AnotherOne extends Zero {}
class Two extends One {}
class Three extends Two {}
console.log((new One).count, (new AnotherOne).count, (new Three).count, Three.count); // 1, 1, 3, 3
Christopher
  • 3,124
  • 2
  • 12
  • 29
  • Without `defineProperty`: `static get count() { … }` – Bergi Oct 01 '22 at 23:14
  • `Object.defineProperty` wasn't incorrect, just unnecessarily complicated :-) But now it's incorrect, OP wanted a `static` class property – Bergi Oct 01 '22 at 23:46
  • 1
    @Bergi, no he asked for `(new One()).count`. Look at the last lines of his example. Anyway, added the static method too. – Christopher Oct 01 '22 at 23:48
  • Oh right, I was confused because the OP *had* a `static` value - and indeed also an prototype getter to retrieve the static value from an instance. – Bergi Oct 01 '22 at 23:52
  • That is exactly what I wanted, so I don't have to repeat that unnecessary line over and over. I really have to dig into the js prototype x) Thank you! – Quentin Oct 02 '22 at 11:58
  • @Quentin then you might take a look at [How does JavaScript .prototype work?](https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work). There are a lot of helpful explainations. – Christopher Oct 02 '22 at 16:02