LEARN HOW TO USE GETTERS AND SETTERS IN JAVASCRIPT

 


Most object-oriented programming languages provide getters and setters, including JavaScript. Developers can use them to access the properties of objects in a secure manner. Setters allow you to modify the values of properties from outside code, while getters allow you to access (“get”) their values. You will learn how to create getters and setters in JavaScript in this tutorial.

CREATING GETTERS AND SETTERS IN JAVASCRIPT

It is possible to store static data and dynamic functions in the same JavaScript object. Methods are functions specific to the object, while properties are static key-value pairs

As an example, a car. The color of a car could be a property. The Car object might have a drive() method. By using a getter, you can access the color property of the Car object, and by using a setter, you can change its value (for instance, from blue to black).

Because methods are not static, you cannot get or set their values with getters and setters.

Getters and setters can be created in three different ways:

  1. In the default method syntax (the getter and setter methods),
  2. By using the get and set keywords,
  3. with the Object.defineProperty() method.

GETTER METHODS

If you want to get the properties of an object, you should define a getter for each property using the default method syntax. Here is an example of how to create getters using this technique. Color and make are the two properties of the myCar object. Using an object literal, you can create it as follows:

var myCar = {   
   color: "blue",
   make: "Toyota"
};

The following code allows you to access the color and make properties directly:

myCar.color;
// blue

myCar.make;
// Toyota

Even though this technique works, using getters instead of directly calling properties has several advantages. For instance,  you can perform operations or checks (e. g. an if-else statement) on the property before retrieving its value.

In order to define getter methods for the color and make properties, follow these steps:

var myCar = { 
   color: "blue", 
   make: "Toyota",

   getColor: function() {
       return this.color;
   },
   getMake: function() {
       return this.make;
   } 
};

The getters above use the this keyword to refer to the object the property belongs to (myCar in the example).. Return statements inside of the getters mean that “return the color / make property value of this object”

In order to get the properties of the myCar object, you need to call the getter methods:

myCar.getColor();
// blue

myCar.getMake();
// Toyota

If you wish, you can also add extra logic to your getter methods. It is possible to get the values of both properties at the same time by creating a getCar() method:

var myCar = { 
    color: "blue", 
    make: "Toyota", 
    
    getCar: function() { 
         return "This is a " + this.color + " " + this.make + "."; 
    } 
};

myCar.getCar();
// This is a blue Toyota.

SETTER METHODS

Setters can also be created using JavaScript’s default method syntax in addition to getters. You can see how setColor() and setMake() compare to previously declared getters in the following table.

var myCar = { 

    /* Properties */
    color: "blue", 
    make: "Toyota", 
    
    /* Getter methods */
    getColor: function() { 
	return this.color; 
    }, 
    getMake: function() { 
	return this.make; 
    },  

    /* Setter methods */
    setColor: function(newColor) {
        this.color = newColor;
    },
    setMake: function(newMake) {
	this.make = newMake;
    }
};

Since setters exist to change the values of properties, they take the new values of the properties (newColor and newMake) as parameters.

To call a setter method, you can do so as follows:

myCar.setColor("red");
myCar.setMake("Audi");

myCar.getColor();
// red

myCar.getMake();
// Audi

You can check with the getters if the new values were correctly set after setting them.

THE GET KEYWORD

An alternative way of creating getters is through the get keyword. Getters can be defined for the myCar. MyCar and color. You can make properties using the get keyword as follows:

var myCar = { 
    /* Data properties */
    defColor: "blue", 
    defMake: "Toyota",
    
    /* Accessor properties (getters) */ 
    get color() { 
         return this.defColor; 
    }, 
    get make() { 
         return this.defMake; 
    }    
};

/* Calling the getter accessor properties */
myCar.color;
// blue

myCar.make;
// Toyota

Remember that the get keyword defines an accessor property rather than a method. As a result, it cannot have the same name as the property that stores the value it accesses. In the above code, defColor and defMake are data properties, while color and make are accessor properties.

You should also call the getter with a property syntax that doesn’t use parentheses after the name of the getter (e.g. myCar.color).

If you wish to support legacy browsers, rather use getter methods since the get keyword is not supported by older Internet Explorer versions (IE8-).

THE SET KEYWORD

Set is a keyword that defines an accessor property that allows you to change a property’s value. The following code shows how you can add setters to it:

var myCar = {
    /* Data properties */
    defColor: "blue", 
    defMake: "Toyota",
    
    /* Accessor properties (getters) */
    get color() { 
         return this.defColor; 
    }, 
    get make() { 
         return this.defMake; 
    },
    
    /* Accessor properties (setters) */
    set color(newColor) {
	this.defColor = newColor;
    },
    set make(newMake) {
	this.defMake = newMake;
    }
};

/* Calling the setter accessor properties */
myCar.color = "red";
myCar.make = "Audi";

/* Checking the new values with the getter accessor properties */
myCar.color;
// red

myCar.make;
// Audi

You can use the same names (color and make) for the setters as well as for the getters, but with parameters (newColor and newMake).. You can pass the new values to the properties using the parameters. Using the assignment operator (equals sign), you can assign the new value to the setters.

The main advantage of using the get and set keywords is that you can keep data properties private. Since the getters and setters have different names (color and make), you won’t accidentally override the data properties (defColor and defMake) with external code.

THE OBJECT.DEFINEPROPERTY() METHOD

To add getters and setters to an already existing object, you can use the defineProperty() method of the global Object. Let’s say you already have the myCar object with defColor and defMake data properties. You can add getters and setters to it later using the Object class. Here is the definition of the Property() method:

/* Original object you already have */
var myCar = { 
    defColor: "blue", 
    defMake: "Toyota"
};

/* Adding a getter and setter to defColor */
Object.defineProperty(myCar, "color", {
	get: function() { 
         return this.defColor; 
    },
	set: function(newColor) {
		this.defColor = newColor;
	},
});

/* Adding a getter and setter to defMake */
Object.defineProperty(myCar, "make", {     
    get: function() { 
         return this.defMake; 
    },
	set: function(newMake) {
		this.defMake = newMake;
	}
});

/* Checking the value of the properties with the getters */
myCar.color;
// blue

myCar.make;
// Toyota

/* Modifying the values with the setters */
myCar.color = "red";
myCar.make = "Audi";

/* Checking the modified properties with the getters */
myCar.color;
// red

myCar.make;
// Audi 

In fact, you can’t only use Object.defineProperty() to modify an existing object but you can add getters and setters to a newly defined object as well. This solution can be useful when you want to make use of the built-in properties of Object.defineProperty(), such as writable or configurable (see the full list in the MDN docs).

CONCLUSION

You don’t have to use getters and setters when creating a JavaScript object, but they can be useful in many situations. Use cases include (1) securing access to data properties, and (2) adding extra logic to properties before they are accessed or set.

*

Post a Comment (0)
Previous Post Next Post