JavaScript OOP ရှိ မိဘ၏ method များကို အစားထိုးခြင်း
ခွဲထွက် class သည် အမည်တူ method ကိုဖန်တီးခြင်းဖြင့် မိဘ၏ method ကို အစားထိုးနိုင်သည်။ ဥပမာတစ်ခုကို ကြည့်ရအောင်။ ကျွန်ုပ်တို့တွင် အောက်ပါမိဘ class ရှိသည်ဆိုပါစို့။
class User {
setName(name) {
this.name = name;
}
getName() {
return this.name;
}
}
ခွဲထွက် class တွင် အမည်တူ method ကို ဖန်တီးကြပါစို့။
class Student extends User {
setName(name) {
}
}
အများအားဖြင့်၊ မိဘ၏ method များကို အစားထိုးရန် လိုအပ်သည်မှာ ထို method ၏ အပြုအမူကို ပြောင်းလဲရန် သို့မဟုတ် ဖြည့်စွက်ရန်ဖြစ်သည်။ ကျွန်ုပ်တို့၏ကိစ္စတွင် အမည်၏အရှည်ကို စစ်ဆေးခြင်းကို ထည့်သွင်းကြပါစို့။
class Student extends User {
setName(name) {
if (name.length > 0) {
this.name = name;
} else {
throw new Error('student name error');
}
}
}
အစားထိုးထားသော method ကိုသာ ခေါ်ယူကြောင်း သေချာစေကြပါစို့။ ပထမဦးစွာ ခွဲထွက် class ၏ object ကို ဖန်တီးပါ။
let student = new Student;
ယခု မှန်ကန်သောတန်ဖိုးကို ပေးသွင်းကာ ကျွန်ုပ်တို့၏ method ကို ခေါ်ယူပါ။
student.setName('john');
ယခု မမှန်ကန်သောတန်ဖိုးကို ပေးသွင်းကာ method ကို ခေါ်ယူပါ။ ရလဒ်အနေဖြင့် console တွင် ပြုလုပ်ထားသောအမှားကို တွေ့မြင်ရပါမည်။
student.setName(''); // error
User class အတွင်း
အသက်၏ getter နှင့် setter ကို ပြုလုပ်ပါ။
Employee class အတွင်း
အသက်၏ setter ကို အစားထိုးပြီး
အသက်သည်
18 နှစ်မှ 65 နှစ်အတွင်းရှိကြောင်း
စစ်ဆေးမှုကို ထည့်သွင်းပါ။