Getters And Setters used in JavaScript Objects....How?

May 15, 2018 0 Comments

Getters And Setters used in JavaScript Objects....How?

 

 



A common object paradigm is to include getter and setter method as attributes. Getter and Setter methods get and set the properties of an object.

Advantages:


  1. You can check if new data is valid before setting a property

  2. You can perform an action on the data which you are getting or setting on a property.

  3. You can control which properties can be stored and retrieved.

An Example showing how Setter is used is shown below:

let person = { name: 'Johnson Ogwuru', _age: 137, set age(newage){ if(typeof newage === 'number'){ this.age = newage; console.log('valid input') } else{ console.log ('Invalid input'); } } }; 

We prepended the property names with underscores . Developers use an underscore to indicate a property or value should not be modified directly by other codes. The setter here makes sure only valid values are added to a particular property, validity here is for the value to be a number, but what happen when we try to add a string to this property? Lets see what adding this line below our code would do;

 person.age = 'Thirty-nine';//returns invalid input console.log(person.age); 

invalid input

From the above we see that on running the Application, we got logged in the console 'invalid value' and we also noticed the value of the age property wasn't changed. But how about we try modifying the age parameter now with the right value. lets see what happens, change the string in the previous code to any number of your choice;

 person.age = 'Thirty-nine';//returns invalid input console.log(person.age); 

valid input

From the above image, our value was accepted as valid and also the value of the age property was modified successfully. That's it for Setters.

Getters are used to get the property value inside of an object. Adding a getter method to our previous example, we would have something like;

let person = { _name: 'Johnson Ogwuru', _age: 137, set age(newage){ if(typeof newage === 'number'){ this.age = newage; console.log('valid input') } else{ return 'Invalid input'; } }, get age(){ console.log(${this._name} is ${this._age} old); return this._age } }; person.age = 'Thirty-nine'; person.age = 39; console.log(person.age); 

Running the above code we have;

Getter image

In Summary:

Getter and Setter methods allow you to process data before accessing or setting property values.

Let's see how we can use setter and getter methods in Es6 classes..... in my next post. LOL


Tag cloud