Getters:
Getters are methods by which we can get and return the internal properties of an object. By the getter method, we can send the values of properties of an object outside of the object.
const person = {
_firstName: 'John',
_lastName: 'Doe',
get fullName() {
if (this._firstName && this._lastName){
return `${this._firstName} ${this._lastName}`;
} else {
return 'Missing a first name or a last name.';
}
}
}
// To call the getter method:
person.fullName; // 'John Doe'
In short, the value passes from the inside of the object to the outside.
Setters:
Setters are methods by which we can reassign or change the value of the existing property of an object. The value will supply from outside of the object.
In short, the value passes from the outside of the object to the inside of the object. Always use getter and setter together in an object
const obj = {
__name: "Mozahedul",
__age: 45,
get person() {
return this.age;
},
set person(val) {
if(typeof val === "number"){
this.age = val;
} else {
console.log("This is not a number");
}
}
}
obj.person = 54;
console.log(obj.person); // Result: 54;
console.log(obj._age); // Result: 54
Post a Comment