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).

JavaScript
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.

JavaScript
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

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