JavaScript Object-Oriented Programming

Introduction

Object-Oriented Programming (OOP) in JavaScript allows you to structure code using objects, classes, and reusable components. Understanding OOP unlocks cleaner architecture and modern development patterns.

1. Objects in JavaScript

const car = {
  brand: "Subaru",
  model: "Impreza",
  drive() {
    console.log("Driving...");
  }
};

car.drive();
    

2. Constructor Functions (Old-School OOP)

function Car(model) {
  this.model = model;
  this.start = function() {
    console.log(this.model + " started!");
  };
}

const c = new Car("WRX");
c.start();
    

3. ES6 Classes (Modern OOP)

Cleaner syntax introduced in ES6.

class Car {
  constructor(model) {
    this.model = model;
  }

  start() {
    console.log(this.model + " started!");
  }
}

const c = new Car("Subaru GX");
c.start();
    

4. Inheritance

Classes can extend other classes.

class Vehicle {
  move() {
    console.log("Vehicle moving...");
  }
}

class Motorcycle extends Vehicle {
  wheelie() {
    console.log("Doing a wheelie!");
  }
}

const m = new Motorcycle();
m.move();
m.wheelie();
    

5. Super Keyword

class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }
}
    

6. Getters and Setters

class User {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name;
  }

  set name(value) {
    this._name = value.trim();
  }
}

const u = new User("Kaloyan ");
console.log(u.name);
    

7. Static Methods

class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtils.add(5, 7));
    

8. Private Fields (#)

Newer JavaScript allows truly private variables.

class BankAccount {
  #balance = 0;

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const acc = new BankAccount();
acc.deposit(100);
console.log(acc.getBalance());
    

Summary