I have the following base class:
class BaseClass {
public static myFlag: boolean = false;
constructor() {
//reference ChildClass.myFlag??
}
}
With the child class:
class ChildClass extends BaseClass {
constructor() { super(); }
}
And the following code:
ChildClass.myFlag = true;
var child = new ChildClass();
How can I reference the value of the child class' myFlag
property without passing the child class to the base class' constructor?
The context of the constructor is the child object. To access the child class' static properties, use Object.prototype.constructor:
class BaseClass {
public static myFlag: boolean = false;
constructor() {
console.log(this["constructor"].myFlag); // true
}
}
Update
In newer versions of TypeScript you might need to do this for it to compile:
class BaseClass {
public static myFlag: boolean = false;
constructor() {
const ctor = this.constructor as typeof BaseClass;
console.log(ctor.myFlag); // true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With