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:
typescriptclass User {
protected cape(str: string) {
return str[0].toUpperCase() + str.slice(1);
}
}
Izveidosim klasi Student, kas manto
no klases User:
typescriptclass Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
}
Pievienosim metodi, kas izvada vārdu:
typescriptclass 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ē:
typescriptclass 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:
typescriptlet student: Student = new Student('john');
Izmantosim metodi, lai izvadītu studenta vārdu:
typescriptconsole.log(student.showName());
Bet mēģinājums izsaukt metodi cape
ārpus klases izraisīs kļūdu:
typescriptconsole.log(student.cape('test')); // kļūda
Dota šāda klase:
typescriptclass 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.