Thuta Learning
JavaScript
IntermediateProgrammingအခြေခံ

Classes & Constructor

JavaScriptသင်ခန်းစာ 1625 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • constructor, instance method, static method ပါတဲ့ class တစ်ခု ရေးနိုင်ဖို့
  • new keyword က နောက်ကွယ်မှာ လုပ်တဲ့ အဆင့်လေးဆင့်ကို ရှင်းပြနိုင်ဖို့
  • Static method ကို class ပေါ်ကနေ၊ instance method ကို object ပေါ်ကနေ ခေါ်ရတဲ့ အကြောင်းရင်းကို ခွဲပြောနိုင်ဖို့
  • Private field (#) နဲ့ getter သုံးပြီး data ကို အပြင်ကနေ မပြင်နိုင်အောင် ကာကွယ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Class ဆိုတာ ကားစက်ရုံရဲ့ ဒီဇိုင်းပုံကြမ်းနဲ့ တူပါတယ်။ ပုံကြမ်းမှာ "ကားတိုင်းမှာ brand, model, year နဲ့ အမြန်နှုန်း ရှိမယ်၊ အရှိန်တင်လို့ရမယ်၊ ဘရိတ်အုပ်လို့ရမယ်" လို့ ရေးထားပါတယ်။ ပုံကြမ်းကိုယ်တိုင်က မောင်းလို့ မရပေမယ့် အဲဒီကနေ ကားအစစ်တွေ အစီးရေ မကန့်သတ် ထုတ်လို့ရပါတယ်။

new Car("Toyota", "Camry", 2023) လို့ ရေးလိုက်တိုင်း ကားအသစ် (instance) တစ်စီး ထွက်လာပြီး constructor ဆိုတဲ့ special method က အဲဒီကားရဲ့ အစ data တွေကို ဖြည့်ပေးပါတယ်။ ကားတစ်စီးချင်းစီမှာ ကိုယ်ပိုင် အမြန်နှုန်း ရှိပေမယ့် accelerate() လို လုပ်ဆောင်ချက်ကိုတော့ ကားအားလုံး မျှဝေသုံးပါတယ်။

Problem → Why → Solution

ပြဿနာ: object တွေကို လက်နဲ့ copy ကူးရေးရင် ပုံစံ ကွဲသွားတယ်

Class မသုံးဘဲ ကား object တွေကို object literal နဲ့ တစ်ခုချင်း ရေးတယ်ဆိုပါစို့။ Method ကို object တိုင်းမှာ ထပ်ခါထပ်ခါ ကူးရေးရပြီး property နာမည် တစ်လုံး စာလုံးပေါင်း မှားတာကိုလည်း ဘယ်သူမှ မစစ်ပေးပါဘူး။ အောက်က car2 မှာ speed အစား sped လို့ မှားရေးမိတော့ accelerate() က undefined + 50 ကို တွက်ပြီး NaN ထွက်လာပါတယ်။

cars.js
const car1 = {
  brand: "Toyota", speed: 0,
  accelerate(amount) { this.speed += amount; },
};
const car2 = {
  brand: "Honda", sped: 0,                     // typo
  accelerate(amount) { this.speed += amount; }, // copied again
};

car2.accelerate(50);
console.log(car2.speed); // NaN

ဘာကြောင့် ဒီ bug က လွယ်လွယ် ဝင်လာတာလဲ

Object တစ်ခုချင်းက ကိုယ့်ပုံစံနဲ့ကိုယ် ရှိနေလို့ "ကားတိုင်းမှာ speed ရှိရမယ်" ဆိုတဲ့ စည်းမျဉ်းကို တစ်နေရာတည်းမှာ မသတ်မှတ်ထားပါဘူး။ Class ရဲ့ constructor ထဲမှာ this.speed = 0 ကို တစ်ခါပဲ ရေးလိုက်ရင် ကားတိုင်းက အဲဒီပုံစံအတိုင်း ထွက်လာပြီး method ကိုလည်း တစ်ကြိမ်ပဲ ရေးရပါတော့တယ်။

Core concept: class, constructor နဲ့ new

Class body ထဲမှာ အပိုင်း သုံးမျိုး ရှိနိုင်ပါတယ် — constructor (instance ဖန်တီးချိန်မှာ တစ်ကြိမ် run)၊ instance method တွေ (object တိုင်းက ခေါ်လို့ရ) နဲ့ static method တွေ (class ကိုယ်တိုင်ပေါ်မှာပဲ ရှိ)။ Object literal နဲ့ မတူတာက method တွေကြားမှာ comma မထည့်ရပါဘူး။ Class body ထဲက code အားလုံးက strict mode နဲ့ အလိုအလျောက် run ပါတယ်။

1. Object အလွတ် ဖန်တီး

new Car(...) က {} အသစ်တစ်ခု ဖန်တီးပါတယ်။

2. Prototype ချိတ်

အဲဒီ object ရဲ့ prototype ကို Car.prototype နဲ့ ချိတ်ပါတယ်၊ ဒါကြောင့် class method တွေကို ရှာတွေ့ပါတယ်။

3. Constructor run

this ကို object အသစ်အဖြစ် ထားပြီး constructor ကို argument တွေနဲ့ ခေါ်ပါတယ်။

4. Object ပြန်ပေး

Constructor ပြီးသွားတော့ ဖြည့်ပြီးသား object ကို new expression ရဲ့ ရလဒ်အဖြစ် ပြန်ပေးပါတယ်။

Instance method တွေကို object တိုင်းထဲ copy မကူးပါဘူး — Car.prototype ဆိုတဲ့ object တစ်ခုတည်းပေါ်မှာ သိမ်းထားပြီး instance အားလုံးက မျှဝေသုံးပါတယ်။ Static method ကတော့ instance တစ်ခုချင်းနဲ့ မဆိုင်တဲ့ အလုပ် (ကားနှစ်စီး နှိုင်းယှဉ်တာ၊ data ကနေ instance ဖန်တီးပေးတဲ့ factory) အတွက်ပါ။ Car.compare(a, b) လို့ class ပေါ်ကနေ ခေါ်ရပြီး myCar.compare ဆိုရင် undefined ပါ။

Class declaration တွေက function declaration လို hoist မဖြစ်ပါဘူး — class ကို မကြေညာခင် new နဲ့ သုံးရင် ReferenceError တက်ပါတယ်။ Class ကို new မပါဘဲ ခေါ်ရင်လည်း TypeError ဖြစ်လို့ constructor function ခေတ်က new မေ့တဲ့ bug ကို ကာကွယ်ပြီးသားပါ။

Constructor ထဲမှာ this.speed = 0 လို့ ရေးမယ့်အစား class body ထိပ်မှာ speed = 0; လို class field အဖြစ်လည်း ကြေညာလို့ရပါတယ်။ Field တွေက constructor body မစခင် instance ပေါ်ကို ထည့်ပေးလို့ argument နဲ့ မဆိုင်တဲ့ အစ value တွေအတွက် ပိုရှင်းပါတယ်။ ဘယ်နည်းနဲ့ပဲ ရေးရေး ရည်ရွယ်ချက်က တစ်ခုတည်းပါ — constructor ပြီးသွားတဲ့အချိန်မှာ object က အသုံးပြုဖို့ အဆင်သင့် ဖြစ်နေရပါမယ်။

မှတ်ထားရမယ့် ပုံစံ
  1. new Car(...) က object အသစ် ဖန်တီး
  2. constructor က this ပေါ် data ဖြည့်
  3. Method တွေက Car.prototype ပေါ်မှာ
  4. Static method တွေက Car ပေါ်မှာပဲ

Data က object တစ်ခုစီမှာ၊ method က prototype တစ်ခုတည်းမှာ၊ static က class မှာ — နေရာ သုံးနေရာ ခွဲမှတ်ပါ။

အထွေထွေ ပုံစံ

javascript
class ClassName {
  #privateField = initialValue;

  constructor(param) {
    this.publicField = param;
  }

  instanceMethod() { /* uses this */ }
  get computed() { return this.#privateField; }
  static helper(a, b) { /* no instance needed */ }
}

#privateField က class ထဲကပဲ ဖတ်လို့ရတဲ့ field ပါ။ get computed() က property လို ဖတ်ရတဲ့ getter ဖြစ်ပြီး static helper() ကို ClassName.helper() လို့ ခေါ်ပါတယ်။ Member တွေကြားမှာ comma မထည့်ပါဘူး။

Example: Car class

Car class မှာ constructor၊ ကားရဲ့ state ကို ပြောင်းတဲ့ (သို့) ဖတ်တဲ့ instance method သုံးခုနဲ့ ကားနှစ်စီးကို နှိုင်းယှဉ်တဲ့ static method တစ်ခု ပါပါတယ်။ နောက်ဆုံး နှစ်ကြောင်းမှာ compare() ကို ကားတစ်စီးပေါ်မှာ မဟုတ်ဘဲ class ကိုယ်တိုင်ပေါ်မှာ Car.compare(...) လို့ ခေါ်ထားပါတယ်: static method ကို ဒီလို သုံးရပါတယ်။

car.js
class Car {
  constructor(brand, model, year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    this.speed = 0;
  }

  accelerate(amount) {
    this.speed += amount;
    return `${this.brand} speed: ${this.speed} km/h`;
  }

  brake() {
    this.speed = 0;
    return `${this.brand} stopped`;
  }

  getInfo() {
    return `${this.year} ${this.brand} ${this.model}`;
  }

  static compare(car1, car2) {
    return car1.year - car2.year;
  }
}

const myCar = new Car("Toyota", "Camry", 2023);
console.log(myCar.getInfo());
console.log(myCar.accelerate(60));
console.log(myCar.accelerate(40));
console.log(myCar.brake());

const oldCar = new Car("Honda", "Civic", 2018);
console.log(Car.compare(oldCar, myCar));

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Lines 2-7constructor(brand, model, year) {

    Argument သုံးခုကို this ပေါ်မှာ သိမ်းပြီး speed ကို 0 နဲ့ စပါတယ်။ ကားတိုင်းက ဒီ property လေးခုနဲ့ပဲ ထွက်လာလို့ problem section က sped typo လို ပြဿနာ မဖြစ်တော့ပါဘူး။

  2. Line 10this.speed += amount;

    this က method ကို ခေါ်တဲ့ object ဖြစ်လို့ myCar.accelerate(60) မှာ myCar ရဲ့ speed ပဲ ပြောင်းပါတယ်။ ဒုတိယ ခေါ်တဲ့အခါ 60 ကနေ 100 ဖြစ်သွားတာက state ကို object က မှတ်ထားလို့ပါ။

  3. Line 23static compare(car1, car2) {

    static ပါလို့ ဒီ method က Car ပေါ်မှာပဲ ရှိပြီး this ကို မသုံးပါဘူး။ ကားနှစ်စီးကို argument အဖြစ် လက်ခံပြီး ထုတ်လုပ်နှစ် ကွာခြားချက်ကို ပြန်ပေးပါတယ်။

  4. Line 28const myCar = new Car("Toyota", "Camry", 2023);

    new က အဆင့်လေးဆင့်လုံးကို လုပ်ပြီး constructor က ဖြည့်ထားတဲ့ object ကို myCar ထဲ ထည့်ပေးပါတယ်။

  5. Line 35console.log(Car.compare(oldCar, myCar));

    Static method ကို class နာမည်နဲ့ ခေါ်ပါတယ်။ 2018 - 2023 = -5 ဖြစ်လို့ အနုတ်ဂဏန်းက ပထမကား ပိုဟောင်းတယ်လို့ ဆိုလိုပါတယ်။ ဒီလို အနုတ်/အပေါင်း ပြန်ပေးတဲ့ ပုံစံကြောင့် cars.sort(Car.compare) လို့လည်း သုံးလို့ရပါတယ်။

You should see
2023 Toyota Camry
Toyota speed: 60 km/h
Toyota speed: 100 km/h
Toyota stopped
-5

Private field (#) နဲ့ getter

Car ရဲ့ speed ကို myCar.speed = 999 လို့ အပြင်ကနေ ပြင်လို့ရနေပါသေးတယ်။ Field နာမည်ရှေ့မှာ # ထည့်လိုက်ရင် class body အပြင်ကနေ ဖတ်တာ၊ ရေးတာ လုံးဝ မရတော့ပါဘူး — account.#balance လို့ ရေးတာကိုယ်တိုင်က SyntaxError ပါ။ အပြင်ကို ဖတ်ခွင့်ပဲ ပေးချင်ရင် getter (get balance()) ကို သုံးပြီး ပြောင်းခွင့်ကိုတော့ စစ်ဆေးမှုပါတဲ့ method ကနေပဲ ပေးပါ။

bank-account.js
class BankAccount {
  #balance = 0;

  deposit(amount) {
    if (amount <= 0) throw new RangeError("Deposit must be positive");
    this.#balance += amount;
  }

  get balance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(500);
console.log(account.balance);        // 500, read through the getter
console.log(Object.keys(account));   // [] - private fields are invisible

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Backend code မှာ API client တစ်ခုကို class အဖြစ် ရေးတာ အရမ်းအဖြစ်များပါတယ်။ new ApiClient({ baseUrl, token }) နဲ့ configuration ကို constructor မှာ တစ်ခါပဲ ပေးပြီး getUser(id)၊ createOrder(data) လို method တွေက baseUrl နဲ့ token ကို this ကနေ ယူသုံးပါတယ်။ Token ကို #token လို private field မှာ ထားရင် log ထုတ်တဲ့အခါ မတော်တဆ ပေါက်ကြားတာကိုလည်း လျှော့ချနိုင်ပါတယ်။

Static method တွေကို factory အဖြစ် သုံးတာလည်း တွေ့ရပါတယ် — User.fromJSON(row) က database row ကနေ User instance ပြန်ဖန်တီးပေးပြီး Date.now()၊ Array.from()၊ Number.isInteger() တို့က built-in static method ဥပမာတွေပါ။ Banking app မှာတော့ BankAccount class က #balance ကို ဖုံးထားပြီး deposit() နဲ့ withdraw() ကနေ အနုတ်ပမာဏ၊ လက်ကျန်မလောက်တာတွေကို ငြင်းပါတယ် — အဲဒီ invalid amount တွေအတွက် test တွေကိုလည်း ရေးထားရပါမယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. Method ထဲမှာ this. ကို မေ့တာ

accelerate(amount) { speed += amount; } လို့ ရေးမိရင် JavaScript က speed ဆိုတဲ့ variable ကို ရှာပြီး မတွေ့လို့ "ReferenceError: speed is not defined" ပေးပါတယ်။ Instance ရဲ့ property ကို အမြဲ this.speed လို့ ရေးရပါတယ်၊ class ထဲမှာ ရှိနေလို့ အလိုအလျောက် မြင်ရတာ မဟုတ်ပါဘူး။

2. Method ကို callback အဖြစ် ခွဲပို့တာ

const stop = myCar.brake; stop(); ဒါမှမဟုတ် callback() လို့ ရိုးရိုးခေါ်တဲ့ function တစ်ခုဆီ myCar.brake ကို ပို့ရင် brake function တစ်ခုတည်းပဲ ရောက်သွားပြီး myCar နဲ့ ချိတ်ဆက်မှု ပျောက်သွားပါတယ်။ Class code က strict mode ဖြစ်လို့ this က undefined ဖြစ်ပြီး this.speed = 0 မှာ TypeError တက်ပါတယ်။ setTimeout(myCar.brake, 1000) က ပိုအန္တရာယ်ရှိပါတယ် — setTimeout က ကိုယ်ပိုင် this (browser မှာ window) ကို ပေးလို့ error မတက်ဘဲ မှားတဲ့ object ကို တိတ်တဆိတ် ပြင်ပါတယ်။ () => myCar.brake() ဒါမှမဟုတ် myCar.brake.bind(myCar) ကို ပို့ပါ။

3. Method တွေကြားမှာ comma ထည့်တာ

Object literal အကျင့်နဲ့ brake() {...}, getInfo() {...} လို့ comma ထည့်မိရင် class body မှာ SyntaxError ဖြစ်ပါတယ်။ Class member တွေကို comma မပါဘဲ တန်းစီရေးရပါတယ်။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • Constructor ထဲမှာ argument တွေကို စစ်ပါ — new Car("", "", -1) လို မမှန်တဲ့ data နဲ့ object ဖန်တီးခွင့် မပေးဘဲ RangeError ဒါမှမဟုတ် TypeError ပစ်ပါ။
  • Constructor ကို state သတ်မှတ်ဖို့ပဲ သုံးပါ၊ network request ဒါမှမဟုတ် file ဖတ်တာလို ကြာတဲ့ အလုပ်ကို static async factory method (await Car.load(id)) ထဲ ရွှေ့ပါ။
  • အပြင်ကနေ မပြင်စေချင်တဲ့ data ကို #field မှာ ထားပြီး ဖတ်ဖို့ getter ပဲ ပေးပါ၊ ပြင်ခွင့်ကို စစ်ဆေးမှုပါတဲ့ method ကနေ ပေးပါ။
  • Instance တစ်ခုနဲ့ မဆိုင်တဲ့ helper ကိုသာ static လုပ်ပါ၊ this ကို သုံးဖို့ လိုတဲ့ method ကို static မလုပ်ပါနဲ့။

Mini challenge

Mini challenge: stock ကို ကာကွယ်ထားတဲ့ Product class

ဆိုင်တစ်ဆိုင်အတွက် Product class တစ်ခု ရေးပါ။ Stock ကို private field မှာ ထားပြီး ရောင်းတဲ့ method ကနေပဲ လျှော့ခွင့်ပေးပါ။

  • constructor(name, price, stock) — stock ကို #stock private field မှာ သိမ်းရမယ်
  • sell(quantity) — stock မလောက်ရင် "Only <n> <name> left"၊ လောက်ရင် လျှော့ပြီး "Sold <qty> <name>" ကို return ပြန်ရမယ်
  • get stock() — လက်ကျန်ကို ဖတ်ခွင့်ပေးရမယ်
  • static cheapest(products) — array ထဲက ဈေးအသက်သာဆုံး product ကို return ပြန်ရမယ်
product.js
class Product {
  // TODO: declare the private #stock field

  constructor(name, price, stock) {
    // TODO: store name and price publicly, stock privately
  }

  sell(quantity) {
    // TODO: refuse when there is not enough stock, otherwise reduce it
  }

  // TODO: a getter named stock

  // TODO: static cheapest(products)
}

// TODO: create Tea (2.5, 10) and Coffee (3, 4), sell 3 tea and 5 coffee,
// then print the tea stock and the cheapest product's name

ရလဒ်: Console မှာ အောက်ပါအတိုင်း ထွက်ရပါမယ်: Sold 3 Tea Only 4 Coffee left Tea left: 7 Cheapest: Tea

အရိပ်အမြွက် ကြည့်ရန်

Private field ကို class body ထိပ်မှာ #stock; လို့ ကြေညာရပြီးမှ constructor ထဲမှာ this.#stock = stock လို့ သုံးလို့ရပါတယ်။ cheapest() အတွက် reduce((best, p) => (p.price < best.price ? p : best)) ကို စဉ်းစားကြည့်ပါ။

အဖြေ ကြည့်ရန်
product.js
class Product {
  #stock;

  constructor(name, price, stock) {
    this.name = name;
    this.price = price;
    this.#stock = stock;
  }

  sell(quantity) {
    if (quantity > this.#stock) {
      return `Only ${this.#stock} ${this.name} left`;
    }
    this.#stock -= quantity;
    return `Sold ${quantity} ${this.name}`;
  }

  get stock() {
    return this.#stock;
  }

  static cheapest(products) {
    return products.reduce((best, p) => (p.price < best.price ? p : best));
  }
}

const tea = new Product("Tea", 2.5, 10);
const coffee = new Product("Coffee", 3, 4);
console.log(tea.sell(3));
console.log(coffee.sell(5));
console.log(`Tea left: ${tea.stock}`);
console.log(`Cheapest: ${Product.cheapest([tea, coffee]).name}`);

Quick Quiz 1 / 3

Example ထဲက myCar ပေါ်မှာ myCar.compare(oldCar, myCar) လို့ ခေါ်ရင် ဘာဖြစ်မလဲ။

Quick Quiz 2 / 3

const c = new Car("Kia", "Rio", 2020); ကို class Car { ... } ကြေညာချက်ရဲ့ အပေါ်မှာ ရေးထားရင် ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

BankAccount class အပြင်ဘက်မှာ console.log(account.#balance) လို့ ရေးရင် ဘာဖြစ်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Class က blueprint ဖြစ်ပြီး constructor က new ခေါ်တိုင်း instance အသစ်ရဲ့ state ကို စတင်သတ်မှတ်ပါတယ်။
  • new က object အလွတ် ဖန်တီး၊ prototype ချိတ်၊ constructor run၊ object ပြန်ပေး — အဆင့်လေးဆင့် လုပ်ပါတယ်။
  • Instance method တွေက prototype ပေါ်မှာ မျှဝေထားပြီး static method တွေကို ClassName.method() လို့ ခေါ်ပါတယ်။
  • #field က class အပြင်ကနေ မမြင်ရလို့ data ကို getter နဲ့ validate လုပ်တဲ့ method တွေကနေပဲ ထုတ်ပေးပါ။

MDN — Using Classes — MDN Web Docs

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။