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).
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-06-28 11:00:00 +0000
Seen: 11 times
Last updated: Jul 14 '21
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?