Modifikators protected TypeScript
Privātās īpašības un metodes netiek mantotas
pēctečiem. Dažreiz tomēr mums ir nepieciešams, lai
īpašība vai metode nebūtu pieejama no ārpuses,
bet tiktu mantota pēctečiem. Šajā
gadījumā jāizmanto modifikators
protected.
Izmēģināsim to praksē. Deklarēsim
mūsu klasē User metodi cape
kā aizsargātu, izmantojot modifikatoru protected:
class User {
protected cape(str: string) {
return str[0].toUpperCase() + str.slice(1);
}
}
Izveidosim klasi Student, kas manto
no klases User:
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
}
Pievienosim metodi, kas izvada vārdu:
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
public showName(): string {
return this.name;
}
}
Un tagad izmantosim aizsargāto metodi vecāka klases iekšpusē pēcteča metodē:
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
public showName(): string {
return this.cape(this.name); // izmantojam vecāka metodi
}
}
Izveidosim mūsu klases objektu:
let student: Student = new Student('john');
Izmantosim metodi, lai izvadītu studenta vārdu:
console.log(student.showName());
Bet mēģinājums izsaukt metodi cape
ārpus klases izraisīs kļūdu:
console.log(student.cape('test')); // kļūda
Dota šāda klase:
class User {
protected name: string;
protected surn: string;
constructor(name: string, surn: string) {
this.name = name;
this.surn = surn;
}
}
Pamantojiet no šīs klases klasi Employee,
kura pievienos aizsargātu īpašību salary,
kā arī visu īpašību getterus, gan savus,
gan mantotos.