Reputation: 99
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
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.
super
even after overridinghttps://basarat.gitbooks.io/typescript/docs/classes.html
Upvotes: 2