JavaScript Class

Public and Private Methods


In object-oriented programming, encapsulation is a fundamental principle that allows us to hide implementation details and expose only the necessary methods and properties to interact with an object. JavaScript, provides various ways to achieve encapsulation. One common approach is through the use of classes. We will explore how to define public and private methods within a JavaScript class. We'll go to the concept of access modifiers in TypeScript and demonstrate how they can be used to control the visibility and accessibility of class methods.

How it Works

TypeScript allows us to explicitly declare access modifiers for class members, including methods. There are three access modifiers available:

Public: accessible from anywhere, both within the class and externally.

Private: only accessible within the class where they are defined. They cannot be accessed or invoked from outside the class.

Protected: similar to private members but can also be accessed by subclasses that inherit from the class.

Let's take a practical example to illustrate the use of public and private methods in a JavaScript class. We'll create a BankAccount class with public and private methods to manage a bank account.

class BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }

  public deposit(amount: number) {
    this.balance += amount;
  }

  public withdraw(amount: number) {
    if (amount <= this.balance) {
      this.balance -= amount;
    } else {
      console.log("Insufficient funds");
    }
  }

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

const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // 1300

In the above code example, we define a BankAccount class with a private balance property and three public methods: deposit(), withdraw(), and getBalance(). The deposit() method allows adding funds to the account, while the withdraw() method deducts funds if the balance is sufficient. The getBalance() method returns the current balance.

We create an instance of the BankAccount class and perform a series of operations, including depositing and withdrawing funds. Finally, we retrieve the updated balance using the getBalance() method.

Conclusion

Defining public and private methods in JavaScript classes, allow us to control the visibility and accessibility of class functionality. This promotes encapsulation and improves code organization, making our codebase more maintainable and secure.

Have a nice code!

Comments