DEV Community

Discussion on: Understanding Object-Oriented Programming (OOP) in JavaScript

Collapse
 
oculus42 profile image
Samuel Rouse

Thanks for posting this! While I mostly recommend against OOP in JavaScript, I think it's an important paradigm to understand.

I think your Abstraction section isn't ideal. The way you define _balance and the related methods inside the constructor mixes actual OOP with closures. The getBalance and deposit methods are not members of the class this way, they are redefined for each instance.

This was how we managed private values prior to ES2022 when Private elements were added to the spec.

Using the private elements simplifies the design makes use of class-level methods.

// Abstraction example with a BankAccount class
class BankAccount {
  // Private variable to hold the balance
  // It cannot be accessed directly outside the class
  #balance

  constructor(owner, balance) {
    this.owner = owner; // account owner's name
    this.#balance = balance;
  }

  // Method to check current balance (controlled access)
  getBalance() {
    return this.#balance;
  }

  // Method to deposit money (changes balance internally)
  deposit(amount) {
    this.#balance += amount;
      console.log(`Deposited ${amount}. New balance: ${this.#balance}`);
  }
}

// Create a new bank account with an initial balance of 1000
const account = new BankAccount("Peace", 1000);

// Deposit money using the provided method
account.deposit(500); // Output: Deposited 500. New balance: 1500

// Access the balance safely through the method
console.log(account.getBalance()); // Output: 1500

// Direct access like account.#balance is not possible (hidden!)
Enter fullscreen mode Exit fullscreen mode