Learn about Getters and Setters in JavaScript

0
4183
getterssetters

getterssetters

A mutator method controls modifications to variables. It’s also known as setter method. A setter is usually followed by a getter – a method which returns the value of a private variable.
Getters and setters provide a useful way to protect data. They also help us set values.
We’re going to start our demonstration by creating a simple student object.

We’ll create a getter for it. It will combine all the information into one sentence, separated by commas.

Now we’ll create a setter. The setter allows the user to send in one value that will be split into 3 values, or 3 parts, thus setting 3 values. The user in this case sends in the entire student object.

We have converted the student details to string using the .toString() method, and then split the string into an array using the .split() method in the commas. The height will be saves in index 0 of parts array, the weight in index 1 of parts array, etc.

Note we do not have to use the setter as a function. The ‘=’ sign is sufficient.  Now we’re going to ‘get’ all the values:

This will print out all of the student’s details.

We can also print out only selected values:

There’s another way to create getters and setters – using defineProperty. For this purpose, lets create a point constructor function named dot.

We’ll start by referencing Object, which is the object that any object in JS inherits from. Inside the defineProperty brackets, we pass in the prototype to attach our new function to. After the comma we defined a name for it, in this case ‘dotAxis’. Inside the curly brackets that follow we define our getters and setters. In this case, our getter simply returns a string of the X and Y coordinates. Next, we create a setter. The function will be passed in a string called thedot as parameter. As before, we split the string into parts which are stored in an array. The splitting occurs in the commas.

Now, let’s create an instance of a dot object:

Now we can call the getters and the setters, like so:

Call the setters:

We can get a hold of the getter with dot1.dotAxis:

The screen output will then be “Point position x : 400 y: 600”
getter setter output

In summary, we’ve seen several ways of creating getters and setters in JavaScript – with and without the use of defineProperty. The setter method allows us to make variables of the same class private and protected. They can only be accessed and changed by the setter method, which takes new values as parameters and uses them to modify the variables.

LEAVE A REPLY

Please enter your comment!
Please enter your name here