Encapsulation allows you to prevent access to properties and methods from the outside. By default, all object properties are public, public, and we can access them from anywhere.
programs.
We can hide them from outside access by making the properties local variables:
//create constructor function Person(name, age) { this.name = name;//let's create an object property var _age = age;//create a local variable //method that will output the name and age of the person //the local variable _age is used in the method this.displayInfo = function () { document.write("Name: " + this.name + "; age: " + _age); }; //getter method that will be used to get the value of the variable from the outside this.getAge = function () { return _age; } //setter method, which is designed to set the value of a variable externally this.setAge = function (age) { _age = age; } } var alex = new Person("Alexander", 33);//create an object console.log(alex._age); // undefined - _age - local variable console.log(alex.getAge()); //get the value of the variable through the getter alex.setAge(34);//let's set the value of the variable using the setter
The Person constructor declares the local variable _age instead of the age property. As a rule, the names of local variables in constructors start with an underscore.
In order to work with the user’s age from the outside, two methods are defined. The getAge() method is for getting the value of the _age variable. This method is also called a getter. The second method is setAge, which is is called a setter (setter), 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 type value is checked