Thuta Learning
ရှာဖွေရန်
IntermediateProgrammingbeginner

Classes & Constructor

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ES6 Classes များသည် objects များဖန်တီးရန် cleaner syntax ဖြစ်သည်။ constructor method သည် object ဖန်တီးသည့်အချိန်တွင် run သည်။

🔑 Class Features:

constructor(): Initialize properties

• Methods: Functions inside class

this: Refers to current instance

static: Class-level methods

javascript
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());
You should see
2023 Toyota Camry Toyota speed: 60 km/h Toyota speed: 100 km/h Toyota stopped