In JavaScript, class getter and setter methods are special methods that allow you to define how the properties of a class are accessed and modified. They provide a way to encapsulate the internal state of an object and add custom logic to the process of getting and setting property values.
Getter methods are used to retrieve the value of a property. They are defined using the get
keyword followed by the method name. When the property is accessed, the getter method is automatically called, and its return value is used as the value of the property.
Setter methods, on the other hand, are used to set the value of a property. They are defined using the set
keyword followed by the method name. When the property is assigned a value, the setter method is automatically called, and the assigned value is passed as an argument to the setter method.
The syntax for defining getter and setter methods within a class is as follows:
class MyClass {
get myProperty() {
// Getter logic
}
set myProperty(value) {
// Setter logic
}
}
- To define a getter method, use the
get
keyword followed by the method name (myProperty
in this example). - To define a setter method, use the
set
keyword followed by the method name (myProperty
in this example), followed by a parameter (value
in this example) that represents the value being assigned to the property. - Inside the getter and setter methods, you can write custom logic to handle the retrieval and assignment of the property value.
- The getter method does not accept any parameters and should return the value of the property.
- The setter method accepts a single parameter (
value
in this example) representing the value being assigned to the property. Inside the setter, you can perform validation or additional processing before assigning the value to the property.
Here’s a simple example demonstrating the syntax:
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
if (value && typeof value === 'string') {
this._name = value;
} else {
console.log('Invalid name.');
}
}
}
const person = new Person('John');
console.log(person.name); // Output: John
person.name = 'Jane';
console.log(person.name); // Output: Jane
person.name = 42; // Invalid name
// Output: Invalid name.
console.log(person.name); // Output: Jane (unchanged)
Note: It is a convention in JavaScript to prefix private properties with an underscore (_
). Although it doesn’t enforce true encapsulation, it indicates that the property is intended for internal use and should not be accessed directly from outside the class.
JavaScript class getter setter example
Here’s an example that demonstrates the usage of getter and setter methods in a JavaScript class:
class Circle { constructor(radius) { this._radius = radius; } get radius() { return this._radius; } set radius(value) { if (value > 0) { this._radius = value; } else { console.log('Invalid radius value. Radius must be greater than 0.'); } } get area() { return Math.PI * this._radius ** 2; } } const circle = new Circle(5); console.log(circle.radius); console.log(circle.area); circle.radius = 10; console.log(circle.radius); console.log(circle.area); circle.radius = -5; console.log(circle.radius);
Output:
Why use getters and setters JavaScript?
Answer: Getters and setters in JavaScript provide benefits like encapsulating the internal state of an object, ensuring data privacy by controlling access to properties. They allow you to enforce validation and error handling when modifying property values, ensuring that assigned values meet specific criteria.
Getters enable you to define computed properties that are derived from other properties or custom logic. Additionally, using getters and setters facilitates compatibility with existing code and frameworks, enhances code maintainability and readability, and enables seamless integration with JavaScript frameworks and libraries.
Difference between getter and setter in JavaScript
The main difference between a getter and a setter in JavaScript is their purpose and the way they are used:
Getter | Setter |
---|---|
Retrieves property value | Modifies property value |
Defined using get keyword | Defined using set keyword |
No parameters | Accepts one parameter (value) |
Used for read-only access or computed properties | Used for controlled write access or validation |
Automatically invoked when accessing the property | Automatically invoked when assigning a value to the property |
Returns a value | Does not return a value |
Comment if you have any doubts or suggestions on this JS class topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version