TypeScript ရှိ protected modifier
Private properties များနှင့် methods များကို သားစဉ်မြေးဆက်များက အမွေဆက်ခံလေ့မရှိပါ။
သို့သော် တစ်ခါတစ်ရံတွင် ကျွန်ုပ်တို့သည် property သို့မဟုတ် method သည် အပြင်မှ ဝင်ရောက်ခွင့်မရှိစေလိုသော်လည်း
သားစဉ်မြေးဆက်များထံတွင် အမွေဆက်ခံရရှိစေလိုပါသည်။ ထိုအခြေအနေတွင်
protected modifier ကို အသုံးပြုသင့်ပါသည်။
လက်တွေ့စမ်းကြည့်ကြပါစို့။ ကျွန်ုပ်တို့၏ class User အတွင်း method cape ကို
protected modifier အသုံးပြု၍ ကာကွယ်ထားသည့် method အဖြစ် ကြေညာပါမည်။
class User {
protected cape(str: string) {
return str[0].toUpperCase() + str.slice(1);
}
}
Class User မှ အမွေဆက်ခံသည့် class Student ကို ဖန်တီးပါမည်။
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
}
အမည်ကို ပြသသည့် method တစ်ခု ထည့်သွင်းပါမည်။
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
public showName(): string {
return this.name;
}
}
ယခု မိဘ class မှ ကာကွယ်ထားသော method ကို သားစဉ်မြေးဆက် class ၏ method အတွင်းမှ အသုံးပြုပါမည်။
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
public showName(): string {
return this.cape(this.name); // မိဘ class ၏ method ကို အသုံးပြုသည်
}
}
ကျွန်ုပ်တို့၏ class ၏ object တစ်ခုကို ဖန်တီးပါမည်။
let student: Student = new Student('john');
ကျောင်းသားကို ပြသရန် method ကို အသုံးပြုပါမည်။
console.log(student.showName());
သို့သော် method cape ကို class အပြင်မှ ခေါ်ယူခြင်းသည် error တစ်ခုကို ဖြစ်စေပါမည်။
console.log(student.cape('test')); // error
အောက်ပါ class ကို ပေးထားပါသည်။
class User {
protected name: string;
protected surn: string;
constructor(name: string, surn: string) {
this.name = name;
this.surn = surn;
}
}
ဤ class မှ class Employee ကို အမွေဆက်ခံပါ။
class Employee သည် ကာကွယ်ထားသော property salary ကို ထပ်မံထည့်သွင်းပြီး
မိမိ၏ property များနှင့် အမွေဆက်ခံရရှိထားသော property များအားလုံး၏ getters များကိုလည်း ထည့်သွင်းပါ။