Encapsulation in JavaScript

Encapsulation is the bundling of data and the methods that act on that data such that access to that data is restricted from outside the bundle, or as Alan Kay describes it, “local retention and protection and hiding of state-process.

const makeNuclearButton = () => {
    let timeWithoutDestruction = 0;
    const passTime = () => timeWithoutDestruction++;
    const totalPeaceTime = () => timeWithoutDestruction;
    const lanuch = () => {
        timeWithoutDestruction = -1;
        return '*';
    }
    setInterval(passTime, 5)

    return {
        // lanuch: lanuch,
        totalPeaceTime: totalPeaceTime
    }
}

const nuclearButton = makeNuclearButton();
nuclearButton.totalPeaceTime();
// lanuch function is not working.
// nuclearButton.lanuch();

if you run lanuch function, it is not going to work.

This is what encapsulation does it is hiding of information that is necessary to be seen by a unauthorized user.

The gets into the idea of principle of least privilege a big security principle when it comes to programming. Also, the thing is you do not want to give anybody access to your APIs.

Leave a Reply

Your email address will not be published.

ANOTE.DEV