JavaScript တွင် OOP ၏ ကာကွယ်ထားသော method များ
Private method များသည် အမွေဆက်ခံခြင်းမရှိပါ နှင့် class အပြင်မှ မမြင်နိုင်ပါ။ သို့သော် တစ်ခါတစ်ရံတွင် အမွေဆက်ခံနိုင်သော်လည်း class အပြင်မှ မမြင်နိုင်သော method များ လိုအပ်ပါသည်။ ထိုသို့သော method များကို ကာကွယ်ထားသော (protected) method များဟု ခေါ်ပါသည်။ JavaScript သည် စိတ်မကောင်းစရာပင် ထိုသို့သော method များကို မပံ့ပိုးပါ။
ထို့ကြောင့် ထိုသို့သော method များကို ဖန်တီးခွင့်ပြုသည့် သဘောတူညီချက်တစ်ခုကို မိတ်ဆက်ရန် အကြံပြုပါသည်။ ထို method များ၏ အမည်များကို အောက်တန်းကြောင်းဖြင့် စတင်ပါမည်။ အမှန်တကယ်တွင် ကျွန်ုပ်တို့သည် private method များအတွက် ရှေးဟောင်းအထွေထွေလက်ခံထားသော သဘောတူညီချက်ကို အသုံးပြုပါမည်။ သို့သော် ၎င်းတို့သည် အမွေဆက်ခံသည်ကို ပြသရန် ထို method များကို ကာကွယ်ထားသည်ဟု ခေါ်ဆိုပြီး ၎င်းတို့ကို အပြင်မှ အသုံးမပြုပါ။ အမှန်မှာ ရှေးဟောင်းသဘောတူညီချက်အရ ၎င်းတို့ကို ထိုနည်းအတိုင်းပင် အသုံးပြုကြသည်။
ထို့ကြောင့် ကာကွယ်ထားသော method ပါရှိသည့် မိဘ class တစ်ခုကို ရေးကြည့်ကြပါစို့။
class User {
setName(name) {
this.name = name;
}
getName() {
return this._capeFirst(this.name);
}
_capeFirst(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
ဤကာကွယ်ထားသော method ကို ဆင်းသက်လာသော class တွင် အသုံးပြုကြည့်ကြပါစို့။
class Student extends User {
setSurn(surn) {
this.surn = surn;
}
getSurn() {
return this._capeFirst(this.surn);
}
}
အောက်ပါကုဒ်တွင် ကူညီပေးသည့် method ကို ကာကွယ်ထားသော method အဖြစ် ပြောင်းလဲပေးပါ။
class User {
setName(name) {
if (this.notEmpty(name)) {
this.name = name;
}
}
getName() {
return this.name;
}
notEmpty(str) {
return str.length > 0;
}
}
class Employee extends User {
setSurn(surn) {
if (this.notEmpty(surn)) {
this.surn = surn;
}
}
getSurn() {
return this.surn;
}
}