🏠 Home / Hub

🟨 JS Lesson 09 — OOP: Classes & Objects

← Back to JS Menu  |  🏠 Hub

1. OOP ဆိုတာ ဘာလဲ?

Object-Oriented Programming = Data (properties) နဲ့ Behavior (methods) ကို Object တစ်ခုထဲ ပေါင်းပြီး code ရေးနည်း
၄ မျိုး: Encapsulation · Inheritance · Polymorphism · Abstraction
// ရိုးရိုး function vs OOP ကွာခြားချက်

// Procedural (old way)
let name = "Ko Ko";
let age = 25;
function greet(n, a) { return `Hi, I'm ${n}, ${a} years old.`; }

// OOP — data + behavior တစ်နေရာတည်းမှာ
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    return `Hi, I'm ${this.name}, ${this.age} years old.`;
  }
}
const p = new Person("Ko Ko", 25);
p.greet(); // "Hi, I'm Ko Ko, 25 years old."

2. Class အခြေခံ

class BankAccount {
  // Constructor — new လုပ်တဲ့အခါ auto run
  constructor(owner, balance = 0) {
    this.owner  = owner;    // public property
    this.balance = balance;
  }

  // Instance method — object တစ်ခုချင်းရဲ့ behavior
  deposit(amount) {
    if (amount > 0) {
      this.balance += amount;
      return `Deposited ${amount}. Balance: ${this.balance}`;
    }
    return "Invalid amount";
  }

  withdraw(amount) {
    if (amount > this.balance) return "Insufficient funds";
    this.balance -= amount;
    return `Withdrew ${amount}. Balance: ${this.balance}`;
  }

  getInfo() {
    return `${this.owner}: $${this.balance}`;
  }
}

// Object (instance) ဆောက်ခြင်း
const acc1 = new BankAccount("Ko Ko", 1000);
const acc2 = new BankAccount("Ma Ma");       // balance = 0

acc1.deposit(500);   // "Deposited 500. Balance: 1500"
acc1.withdraw(200);  // "Withdrew 200. Balance: 1300"
acc2.getInfo();      // "Ma Ma: $0"

// Properties access
acc1.owner;    // "Ko Ko"
acc1.balance;  // 1300

3. Static Methods & Properties

class MathHelper {
  static PI = 3.14159;   // static property — class ကိုယ်တိုင်ပိုင်

  // static method — instance မဆောက်ဘဲ သုံးလို့ရ
  static add(a, b) { return a + b; }
  static multiply(a, b) { return a * b; }
  static circleArea(r) { return MathHelper.PI * r * r; }

  // Count instances (static use case)
  static count = 0;
  constructor() { MathHelper.count++; }
}

// Static — class ကနေ တိုက်ရိုက်ခေါ်
MathHelper.add(5, 3);         // 8
MathHelper.multiply(4, 6);    // 24
MathHelper.circleArea(5);     // 78.53975
MathHelper.PI;                // 3.14159

const m1 = new MathHelper();
const m2 = new MathHelper();
MathHelper.count;             // 2

// ⚠️ instance ကနေ static ခေါ်လို့မရ
// m1.add(1,2) → TypeError

4. Private Fields (#)

class User {
  // Private fields — class အပြင်ကနေ access မရ
  #password;
  #loginAttempts = 0;

  constructor(username, password) {
    this.username = username;   // public
    this.#password = password;  // private
  }

  login(inputPassword) {
    if (this.#loginAttempts >= 3) {
      return "Account locked!";
    }
    if (inputPassword === this.#password) {
      this.#loginAttempts = 0;
      return "Login successful!";
    }
    this.#loginAttempts++;
    return `Wrong password. Attempts: ${this.#loginAttempts}/3`;
  }

  changePassword(old, newPass) {
    if (old !== this.#password) return "Wrong old password";
    this.#password = newPass;
    return "Password changed!";
  }
}

const user = new User("ko_ko", "secret123");
user.login("wrong");       // "Wrong password. Attempts: 1/3"
user.login("secret123");   // "Login successful!"

// ⚠️ Private မရ
// user.#password  → SyntaxError
// user.password   → undefined
💡 # = JavaScript native private (ES2022) | _ prefix (old convention) = "please don't use" but still accessible

5. Getters & Setters

class Temperature {
  #celsius;

  constructor(celsius) {
    this.#celsius = celsius;
  }

  // getter — property လိုသုံးလို့ရ (method ကိုမဟုတ်)
  get fahrenheit() {
    return (this.#celsius * 9/5) + 32;
  }

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

  // setter — validation ထည့်လို့ရ
  set celsius(value) {
    if (value < -273.15) throw new Error("Below absolute zero!");
    this.#celsius = value;
  }

  get description() {
    if (this.#celsius < 0)   return "Freezing ❄️";
    if (this.#celsius < 20)  return "Cold 🧥";
    if (this.#celsius < 30)  return "Comfortable 😊";
    return "Hot 🔥";
  }
}

const temp = new Temperature(25);
temp.fahrenheit;   // 77   (property syntax, not method call!)
temp.celsius;      // 25
temp.description;  // "Comfortable 😊"

temp.celsius = 100;  // setter called
temp.celsius = -300; // throws Error

6. Live Demo

Output ဒီမှာ ပေါ်မယ်...

📌 Class Quick Reference

ConceptSyntaxAccessible From
Public propertythis.name = xAnywhere
Private field#name = xClass only
Static propertystatic count = 0Class (not instance)
Constructorconstructor(args) {}auto called on new
Instance methodmethodName() {}Instance
Static methodstatic fn() {}Class only
Getterget prop() {}obj.prop (no ())
Setterset prop(v) {}obj.prop = val

← JS 08  |  Next: JS 10 → Inheritance & Polymorphism →

📌 Study Checklist