1 | initial version |
Yes, it is possible to have different values for a property when calling both super.property
and this.property
in a class that extends in TypeScript.
When calling super.property
, the class is accessing the parent class's implementation of the property. If the parent class has initialized the property with a certain value, that value will be used when accessing super.property
.
When calling this.property
, the class is accessing its own instance of the property. If the property has been reinitialized with a different value in the child class, that value will be used when accessing this.property
.
Here's an example:
class Parent {
property: number = 5;
}
class Child extends Parent {
constructor() {
super();
this.property = 10; // reinitialized with a different value
}
logValues() {
console.log(super.property); // logs 5 (value of parent class's property)
console.log(this.property); // logs 10 (value of child class's property)
}
}
const child = new Child();
child.logValues(); // logs "5" and "10"
In this example, the Child
class extends the Parent
class and reinitializes the property
property with a different value in its constructor. When calling logValues()
on an instance of the Child
class, we can see that super.property
returns the value of the parent class's property (5) while this.property
returns the value of the child class's property (10).