Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use static property of extended class in super()

Suppose we have the code

class A {
  static foo = 1;
  constructor() {
    console.log(A.foo);
  }
}
class B extends A {
  static foo = 2;
  constructor() {
    super();
  }
}
new A(); // prints "1"
new B(); // also prints "1", but make it print "2"

Here the constructor of A is accessing A.foo. When A is extended to B with a new value of foo, the constructor still prints 1, the value of A.foo, when really I want it to print the value of B.foo.

How would I modify this code such that the constructor prints the foo property of the current class?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the constructor property to get access to the class itself, then you can refer to the static property from that.

class A {
  static foo = 1;
  constructor() {
    console.log(this.constructor.foo);
  }
}
class B extends A {
  static foo = 2;
  constructor() {
    super();
  }
}
new A(); // prints "1"
new B(); // also prints "1", but make it print "2"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading