Getters and Setters in JavaScript Classes (Live Playground)
In JavaScript classes, getters and setters are special methods used to access and modify properties of class instances. In this tutorial, we'll explore the syntax and usage of getters and setters in JavaScript classes.
Getters and Setters Syntax
To define a getter or a setter, use the get
or set
keyword followed by the method name within the class body:
class Circle {
constructor(radius) {
this._radius = radius;
}
// Getter for radius
get radius() {
return this._radius;
}
// Setter for radius
set radius(value) {
if (value <= 0) {
console.log('Radius must be greater than zero.');
} else {
this._radius = value;
}
}
}
In this example, we've defined a getter and a setter for the radius
property.
Using Getters and Setters
Getters and setters can be called as if they were regular properties:
const myCircle = new Circle(5);
console.log(myCircle.radius); // 5
myCircle.radius = 10;
console.log(myCircle.radius); // 10
myCircle.radius = -5; // Radius must be greater than zero.
In this example, we've created a new Circle
instance, accessed its radius
property using the getter, and modified it using the setter.
Conclusion
In this tutorial, we learned about getters and setters in JavaScript classes, their syntax, and usage. Getters and setters allow you to control access and modification of class properties, which makes your code more robust and easier to maintain.