start learning
Image 1
4401021425747

Encapsulation JavaScript Object-Oriented Programming (OOP)

Encapsulation ensures that the internal state and implementation details of an object are hidden and can only be accessed and modified through controlled interfaces, promoting data integrity and abstraction.


Private Variables using Closure


function Counter() {
  let count = 0;

  this.increment = function() {
    count++;
  };

  this.getCount = function() {
    return count;
  };
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // Output: 1

In this example, encapsulation is achieved by using closure. The Counter function creates a private variable count and returns two public methods increment and getCount that can access and modify the private count variable. The private count variable is only accessible through these methods, ensuring encapsulation.


Getters and Setters


class BankAccount {
  constructor(initialBalance) {
    let balance = initialBalance;

    this.getBalance = function() {
      return balance;
    };

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

    this.withdraw = function(amount) {
      if (amount <= balance) {
        balance -= amount;
      } else {
        console.log('Insufficient funds');
      }
    };
  }
}

const account = new BankAccount(2000);
console.log(account.getBalance()); // Output: 2000
account.deposit(750);
console.log(account.getBalance()); // Output: 2750
account.withdraw(4000); // Output: Insufficient funds

In this example, encapsulation is achieved using getter and setter methods. The BankAccount class has a private variable balance which can only be accessed or modified through the getBalance, deposit, and withdraw methods. These methods provide controlled access to the private variable and allow performing appropriate operations while maintaining encapsulation.


Symbol-based Private Members


const _name = Symbol('name');

class Person {
  constructor(name) {
    this[_name] = name;
  }

  getName() {
    return this[_name];
  }
}

const person = new Person('JohnY');
console.log(person.getName()); // Output: JohnY
console.log(person[_name]); // Output: undefined

In this example, encapsulation is achieved using symbols to create private members. The _name symbol is used as a private property in the Person class, which can only be accessed using the getName method. Attempting to access the private property directly using person[_name] will return undefined, thereby encapsulating the private member.


Feel free to copy the code and experiment with our javascript compiler


Output:

×