JavaScript OOP တွင် Context ဆုံးရှုံးခြင်း
Classes များဖြင့် အလုပ်လုပ်သောအခါ context ဆုံးရှုံးတတ်ပြီး
this သည် class object ကို ညွှန်မည့်အစား အခြားတစ်ခုခုကို
ညွှန်နေတတ်ပါသည်။
ထိုသို့ဖြစ်ရပုံနှင့် ဘယ်လိုဖြေရှင်းရမည်ကို ကြည့်ကြပါစို့။
ကျွန်ုပ်တို့တွင် User class ရှိသည်ဆိုပါစို့။
၎င်းသည် user ၏အမည်နှင့် ထို user ရောက်ရှိခဲ့သော
မြို့များ array ကို ပါဝင်သည်။
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
မြို့များကို ထုတ်ပြသည့် method တစ်ခု ရှိသည်ဆိုပါစို့။
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
ဤ method ထဲတွင် class ၏ အထောက်အကူ method တစ်ခုခုကို အသုံးပြုရန် ဆုံးဖြတ်လိုက်သည်ဆိုပါစို့။ ဤအခြေအနေတွင် context ဆုံးရှုံးသွားပါမည်။
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // context ဆုံးရှုံးသွားပြီ
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
ပြဿနာကို ဥပမာ၊ arrow function ကိုအသုံးပြု၍ ပြင်ဆင်နိုင်ပါသည်။
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(city => {
console.log(this.#cape(city));
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
အောက်ပါ code တွင်ကျူးလွန်ထားသော အမှားကို ပြင်ဆင်ပေးပါ။
class Employee {
constructor(name, salary, coeffs) {
this.name = name;
this.salary = salary;
this.coeffs = coeffs;
}
getTotal() {
return this.coeffs.reduce(function(res, coeff) {
return res + this.salary * coeff;
}, 0);
}
}
let employee = new Employee('john', 1000, [1.1, 1.2, 1.3]);
let total = employee.getTotal();
console.log(total);