JavaScript OOP တွင် Private Methods များ
Property များသာမက method များကိုလည်း private အဖြစ်သတ်မှတ်နိုင်ပါသည်။ ပုံမှန်အားဖြင့် အကူအညီပေးသော method များကို class အပြင်ဘက်မှ မခေါ်မိစေရန် private အဖြစ်လုပ်လေ့ရှိပါသည်။
ဥပမာတစ်ခုဖြင့် ကြည့်ကြပါစို့။ ကျွန်ုပ်တို့တွင် အောက်ပါ class ရှိသည်ဆိုပါစို့။
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#name;
}
}
ဤ class အတွင်းတွင် string တစ်ခုကို parameter အဖြစ်လက်ခံကာ ၎င်း၏ ပထမအက္ခရာကို အကြီးအက္ခရာ ပြောင်းပေးသည့် private method တစ်ခုကို ဖန်တီးကြပါစို့။
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#name;
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
ကျွန်ုပ်တို့၏ အကူအညီပေးသော method ကို အခြား method တစ်ခုအတွင်းမှ အသုံးပြုကြည့်ပါမည်။
class User {
#name;
constructor(name) {
this.#name = name;
}
show() {
return this.#cape(this.#name);
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
စမ်းကြည့်ကြပါစို့။ ကျွန်ုပ်တို့၏ class object တစ်ခုကို ဖန်တီးပါမည်။
let user = new User('john');
အကူအညီပေးသော method ကို အသုံးပြုသည့် public method ကို ခေါ်ကြည့်ပါမည်။
console.log(user.show());
အောက်ပါ code တွင် အကူအညီပေးသော method ကို private အဖြစ်ပြောင်းလဲပါ။
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
getSalary() {
return this.addSign(this.salary);
}
addSign(num) {
return num + '$
;
}
}