Следите за новинками
в нашем Telegram канале. Жми, чтобы подписаться:)
⊗jsOpAdCL 41 of 60 menu
◀ ▶

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);
← →
↑
မြန်မာ▼
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEnglishEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
ဝက်ဘ်ဆိုက် လုပ်ဆောင်ခြင်း၊ ဆန်းစစ်လေ့လာခြင်းနှင့် ပုဂ္ဂလိကပြုပြင်ခြင်းအတွက် ကျွန်ုပ်တို့သည် cookie များကို အသုံးပြုပါသည်။ ဒေတာများကို ပြုပြင်ခြင်းသည် ကိုယ်ရေးကိုယ်တာ မူဝါဒအတိုင်း ဖြစ်ပါသည်။
အားလုံးလက်ခံရန် ပြင်ဆင်ရန် ငြင်းပယ်ရန်