JavaScript Advanced Day 2: Advanced Objects & Classes

Goal of this Day

Today you will learn:

By the end, you will create robust classes with encapsulation and methods.

Step 1: ES6 Classes

Use the class keyword to define objects:


class Person {
  #age;
  constructor(name, age) {
    this.name = name;
    this.#age = age;
  }
  getAge() {
    return this.#age;
  }
}

const john = new Person("John", 30);
console.log(john.getAge()); // 30

Step 2: Getters & Setters

Encapsulate access to private fields:


class Person {
  #age;
  constructor(name, age) {
    this.name = name;
    this.#age = age;
  }

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

  set age(value) {
    if(value >= 0) this.#age = value;
  }
}

const alice = new Person("Alice", 25);
console.log(alice.age); // 25
alice.age = 30;
console.log(alice.age); // 30

Step 3: Methods & this nuances

Methods inside classes use this to access properties:


class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }
}

const bob = new Person("Bob");
bob.greet(); // Hi, I'm Bob

Practice


class Person {
  #age;
  constructor(name, age) {
    this.name = name;
    this.#age = age;
  }
  getAge() { return this.#age; }
}

const john = new Person("John", 30);
console.log(john.getAge());

Task

Create a BankAccount class:

Example:


class BankAccount {
  #balance;
  
  constructor(initialBalance = 0) {
    this.#balance = initialBalance;
  }
  
  deposit(amount) {
    if(amount > 0) this.#balance += amount;
  }
  
  withdraw(amount) {
    if(amount <= this.#balance) this.#balance -= amount;
  }
  
  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
console.log(account.getBalance()); // 120