Tuesday, November 13, 2018

TypeScript - Classes - this keyword - constructors

Now, in the below example, elevation is a protected variable.

class Visakhapatnam extends City{
name = "Visakhapatnam";
protected elevation = 45;

constructor(){
super("Visakhapatnam");
}
}

We can also modify it inside the constructor by using this keyword. 

class Visakhapatnam extends City{
name = "Visakhapatnam";
constructor(){
super("Visakhapatnam");
this.elevation = 45;
}
}

const cityVisakha = new Visakhapatnam();
console.log(cityVisakha);
console.log(cityVisakha.name);
cityVisakha.setType("Town");
console.log(cityVisakha.printType());
console.log(cityVisakha.getElevation());
console.log(cityVisakha);

Now, if i compile:

$ tsc
$

and .. check in the console.  

Console Output:

Visakhapatnam elevation: 45name: "Visakhapatnam"type: "Town"__proto__: City
city-App.ts:138 Visakhapatnam
city-App.ts:109 new type = Town
city-App.ts:113 Town
city-App.ts:140 undefined
city-App.ts:104 45
city-App.ts:141 undefined
city-App.ts:142 Visakhapatnam

We can see, that using the this keyword - the elevation was updated. Note that we cannot update the type using the this keyword. This is because, private properties are not accessible using the this keyword in the child classes.


No comments:

Post a Comment