JavaScript Encapsulation

Encapsulation is one of the key concepts of object-oriented programming and represents hiding the state of an object from direct access from the outside. By default, all object properties are public, and accessible, and we can access them from anywhere in the program.

function User(pName, pAge) {
    this.name = pName;
    this.age = pageAge;
    this.displayInfo = function(){
        document.write("Name: " + this.name + "; age: " + this.age);
    };
};
var tom = new User("Tom", 26);
tomname=34;
console.log(tom.name);

But we can hide them from outside access by making the properties local variables:

function User (name, age) {
    this.name = name;
    var_age = age;
    this.displayInfo = function(){
        document.write("Name: " + this.name + "; age: " + _age + " <br>");
    };
    this.getAge = function() {
        return _age;
    }
    this.setAge = function(age) {
        if(typeof age === "number" && age >0 && age < 110){
            _age = age
        } else {
            console.log("Invalid value");
        }
    }
}

var tom = new User("Tom", 26);
console.log(tom._age); // undefined - _age - local variable
console.log(tom.getAge()); // 26
tom.setAge(32);
console.log(tom.getAge()); // 32
tom.setAge("54"); // Invalid value

The User constructor declares a local variable _age instead of a property age. As a rule, the names of local variables in constructors begin with an underscore.

In order to work with the user’s age externally, two methods are defined. The method getAge() is designed to get the value of the _age variable. This method is also called a getter. The second method – setAge, which is also called a setter, is designed to set the value of the _age variable.

The advantage of this approach is that we have more control over access to the _age value. For example, we can check some accompanying conditions, as in this case, the type value is checked (it must represent a number), and the value itself (age cannot be less than 0).