Thuta Learning
IntermediateProgrammingbeginner

Classes & Constructor

Relax. We'll talk through this in plain words — no textbook voice.

ES6 Classes give you a cleaner syntax for creating objects. constructor method runs when an object is created.

🔑 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
Classes & Constructor | Thuta Learning