Getter And Setter For JS Objects

Introduction

 
Let's look at a different type of JavaScript object and add the getter and setter on it.
 
Here is a JavaScript JSON object.
  1. let training = { name: { firstname: "c#", lastName: ".net" }, hour: "4" }  
We can add a new property "fullname" which will be kind of dynamic/calculated property, using JS Object.defineProperty.
  1. Object.defineProperty(traning, "fullname",  
  2.     {  
  3.         get: function () {  
  4.             return this.name.firstname + this.name.lastName  
  5.         },  
  6.         set: function (value) {  
  7.             var s = value.split(' ')  
  8.             this.name.firstname = s[0]  
  9.             this.name.lastName = s[1]  
  10.         }  
  11.     })  
Now, you can directly get the full name of any training object by calling the training.fullname.
 
You can also set this property in the same way, i.e., training.fullname = "java script".
 
Let's have another example of an array.
  1. var trainings = [ "c#", /".netcore""javascript""html""angular"]  
JS does not provide default extension on the array, like first, last, etc. You can define your own properties. 
  1. Object.defineProperty(trainings, "first",      
  2.     {  
  3.         get: function () {  
  4.             return this[0];  
  5.         }  
  6.     })  
  7.   
  8. Object.defineProperty(trainings, "last",  
  9.     {  
  10.         get: function () {  
  11.             return this[this.length - 1]  
  12.         }  
  13.     })  
But if you notice that these new properties are defined only for specific training array, you can define these properties to all instances of an array by setting an array prototype. If you are not familiar with prototype/inheritance in JS, please have a look at my next article.
  1. Object.defineProperty(Array.prototype, "first",  
  2.     {  
  3.         get: function () {  
  4.             return this[0];  
  5.         }  
  6.     })  
  7.   
  8. Object.defineProperty(Array.prototype, "last",  
  9.     {  
  10.         get: function () {  
  11.             return this[this.length - 1]  
  12.         }  
  13.     })  
I hope you learned how to implement getter and setter for JS objects and how to apply class like array etc., directly