Introduction
JavaScript is an object-oriented programming language and encapsulation is a pillar of object-oriented programming language. Properties help us to encapsulate. Properties help us to control what is assigned and return to and from the public field.
A Property is a member that helps us to read, write, or compute the value of a private field using get and set accessor.
Properties can be of the type,
- Read-write (they have both get and set accessor)
- Read-only (they will have to get accessor)
- Write only (they will have set accessor)
In JavaScript in order to create properties we can use Object.defineProperty() method.
DefineProperty() method takes three parameters,
- The object on which we want to define property
- Name of the property to be defined
- The descriptor for the property being defined or modified
Descriptor can be a data descriptor or accessor descriptor. Accessor descriptor have the following keys,
- get which serves as a getter for the property, the function return will be used as the value of the property
- set which serves as a setter for the property and will be used to assign the value to the property.
Example
Now let’s create a constructor function Person as below, this function has three private variables _name, _address, and _salary.
Using defineProperty() method let’s create,
- name - Read-only property using get key
- address - Write only property using set key
- salary - Read/Write property using get and set key
Let’s initialize _name and _address private variable with some default value.
- <script type="text/javascript">
- function Person() {
- var _name = "Mary";
- var _address = "Houston";
- var _salary;
- //Read only Property
- Object.defineProperty(this, "name", {
- get: function() {
- return _name;
- },
- })
- //Write Only Propert
- Object.defineProperty(this, "address", {
- set: function(value) {
- _address = value;
- }
- })
- //Read or Write Property
- Object.defineProperty(this, "salary", {
- get: function() {
- return _salary;
- },
- set: function(value) {
- if (value < 1) alert("Invalid Salary");
- else _salary = value;
- }
- })
- }
- var person = new Person();
- person.name = "Jane";
- person.address = "Austin";
- person.salary = 10;
- person.salary = -1;
- var result = person;
- </script>





pravesh kumarPosted Sep 8, 2017, 5:16 AM
Nice explanation.. :)