techStackGuru

JavaScript Encapsulation


In JavaScript, encapsulation refers to the act of binding data and functions together. Encapsulation refers to the concept of data hiding, or the concept that an objects internal entities should not be exposed as public entities.


Encapsulation can be done in two ways

  • Making data members private
  • Using setter methods and getter methods

Problem before Encapsulation


var animal = {
    sound : "quack",
};
  
console.log(animal.sound); // quack
animal.sound = "howl";
console.log(animal.sound); // howl

Everything appears to be in order, but what if someone unintentionally or maliciously misuses this object?


animal.sound = "17";
console.log(animal.sound); // 17

It is completely acceptable to do so. A variable in JavaScript can take any form of data as its value. We may, however, wish to limit it to only valid characters. For that purpose we use encapsulation.


Example of Encapsulation


class Animal
  {
    constructor() {
       var sound;
    }
        
    getSound() {
       return this.sound;
    }
        
    setSound(sound) {
       this.sound=sound;
    }
}

var bark=new Animal();
bark.setSound("quack");

console.log(bark.getSound());

Output

quack

previous-button
next-button