Getters and setters are special methods that allow you to define how to access and mutate the properties of a class.
getterSetter.js
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
// Getter
get age() {
return this._age;
}
// Setter
set age(value) {
if (value < 0) {
console.log('Age cannot be negative.');
} else {
this._age = value;
}
}
}
const person1 = new Person('Krishna', 35);
console.log(`Age : ${person1.age}`);
person1.age = -5;
person1.age = 45;
console.log(`Age : ${person1.age}`); // Output: 45
Output
Age : 35 Age cannot be negative. Age : 45
Getter method
get age() {
return this._age;
}
The getter method is used to retrieve (or "get") the value of the _age property. When you access person1.age, JavaScript automatically calls the get age() method. This method returns the value of _age, allowing you to read it without directly accessing the _age property.
Setter Method// Setter
set age(value) {
if (value < 0) {
console.log('Age cannot be negative.');
} else {
this._age = value;
}
}
The setter method is used to set or update the value of the _age property. When you assign a value to person1.age (e.g., person1.age = 45), JavaScript automatically calls the set age(value) method. The method checks if the value is negative. If it is, it prints a warning message; otherwise, it updates _age with the new value.
No comments:
Post a Comment