Manish
Manish

Reputation: 99

Unable to access parent class properties

Please see the TypeScript code below:

class x {
  a = 20;
  f1(){
    console.log("parent > " + this.a);
  }
}
class y extends x {
  a = 10;
  f1(x?:number){
     console.log("chold > " + this.a);
    super.f1();
  }
}
let z = new y();
z.f1();

When I run the below compiled code in Chrome, I get child = 10 and parent = 10 .

What is the correct way of accessing parent class properties from parent class as this does not seem to work.

Upvotes: 0

Views: 2208

Answers (1)

basarat
basarat

Reputation: 275927

What is the correct way of accessing parent class properties from parent class as this does not seams to work.

this points to the current instance. this.a will point to the same value in the parent and the class. Essentially, a is overridden and when the parent accesses this.a it accesses the child property.

More

  • Parent methods are accessible via super even after overriding
  • Parent properties are overridden permanently

Docs

https://basarat.gitbooks.io/typescript/docs/classes.html

Upvotes: 2

Related Questions