Ask Your Question
1

Is it possible to have different values for a property when calling both super.property and this.property in a class that extends in TypeScript?

asked 2021-06-28 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-07-14 11:00:00 +0000

lakamha gravatar image

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).

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-06-28 11:00:00 +0000

Seen: 11 times

Last updated: Jul 14 '21