Encapsulation and Privacy in JavaScript OOP

Lesson Overview

Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Imagine encapsulation as an invisible fence safeguarding a garden from outside interference, keeping data and methods safe within. Within this garden, certain plants (Private Attributes and Methods) are only for the gardener's eyes. These are crucial for making your classes more robust and secure!

Encapsulation Explained

Encapsulation in OOP wraps up data and methods into a class. This organizational approach tidies the code and reinforces security. If you were to code a multiplayer game, for example, you could create a Player class, encapsulating data (health, armor, stamina) and methods (receiveDamage, shieldHit, restoreHealth).

class Player {
    constructor(health, armor, stamina) {
        this.health = health;
        this.armor = armor;
        this.stamina = stamina;
    }

    receiveDamage(damage) {
        this.health -= damage;  // Reduce health
    }

    shieldHit(armor) {
        this.armor -= armor;  // Decrease armor
    }

    restoreHealth(healthIncrease) {
        this.health += healthIncrease;  // Restore health
    }
}

const player = new Player(100, 50, 77);

Now, player is an instance of the Player class on which you can call methods.

Remark the Privacy

In JavaScript, a # before the attribute or method name designates it as private. Note that the constructor itself cannot be private.

class PrivateExample {
    #privateAttribute;  // Declare a private field

    constructor() {
        this.publicAttribute = "Public";
        this.#privateAttribute = "Private";  // Initialize private attribute
    }

    getPrivateAttribute() {
        return this.#privateAttribute;
    }
}

const example = new PrivateExample();
console.log(example.publicAttribute);  // Works: logs "Public"
console.log(example.getPrivateAttribute());  // Works: logs "Private"
console.log(example.#privateAttribute);  // Error: can't access private attribute from outside

Private attributes and methods are inaccessible directly from an instance. This arrangement helps maintain integrity.

Private Attributes

Private Attributes, which can only be altered via class methods, limit outside interference. For instance, a BankAccount class might feature a #balance private attribute that one could change only through deposits or withdrawals.

class BankAccount {
    #balance;  // Declare a private field

    constructor(accountNumber, balance) {
        this.accountNumber = accountNumber;
        this.#balance = balance;  // Initialize the private attribute
    }

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

    getBalance() {
        return this.#balance;  // A public method to access balance
    }
}

const bankAccount = new BankAccount(1234, 100);
console.log(bankAccount.getBalance());  // Works: logs 100
console.log(bankAccount.#balance);  // Error: can't access private attribute from outside

Here, #balance is private, thus ensuring the integrity of the account balance. It can't be accessed directly from outside the class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal