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?
>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"