Classes

Defining a Class

Example

A class is a blueprint for objects. constructor runs when you create an instance with new:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  deposit(amount) {
    this.balance += amount;
    return this;            // allows chaining
  }
  toString() {
    return `${this.owner}: ₹${this.balance}`;
  }
}
const acc = new BankAccount("Asha", 500);
acc.deposit(200).deposit(100);
console.log(acc.toString());
console.log(acc instanceof BankAccount);

Output

Asha: ₹800
true

Class Fields

Example

Properties can be declared directly in the class body:

class Counter {
  count = 0;
  step = 1;
  increment() { this.count += this.step; return this.count; }
}
const c = new Counter();
c.increment(); c.increment();
console.log(c.count);

Output

2