Getter and Setter are property which are defined inside object/classes. both are the type of function, by which we can get and set value of property in object.
Before going to details of Getter & Setter, first let see why do we need this.
Why we need?
suppose you have following Student object,
let Student = {
name : 'Getter',
marks : {
python : 80,
js: 85,
}
}
Now you want to calculate total marks.
some of the way to get total marks are,
const total = Student.marks.python + Student.marks.js;
creating getTotalMarks method in Student object
let Student = {
name : 'Getter',
marks : {
python : 80,
js: 85,
},
getTotalMarks() {
return this.marks.python + this.marks.js
}
}
and by calling Student.getTotalMarks() we will get the total marks
Above solution works. but syntax is not cleaner ( Getter & Setter have many advantages over traditional method ). How if we get total marks, simple as property name? like Student.totalMarks.
Here getter are come into picture.
let Student = {
name : 'Getter',
marks : {
python : 80,
js: 85,
},
get getTotalMarks() {
return this.marks.python + this.marks.js
}
}
and now we can get total marks simply as,
const total = Student.getTotalMarks;
1. Getter :
below is the description of Getter from MDN,
Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter.
Getter function are declared with get keyword,
e.g :
{
get functionName() {}
}
Click here to read more about Getter
2. Setter
all properties/advantages of Setter are same as Getter. Except Getter are used to get computed value from object where as Setter are used to set desirable value to property.
Setter function are declared with set keyword,
e.g. :
{
set functionName() {}
}
- Below is sample program using Setter,
let Student = {
name : 'Setter',
marks : {
python : 80,
js: 85,
},
}
Now, suppose we want to ensure that user must enter marks between 0 - 100. so, for this we can use Setter function
let Student = {
name: "Setter",
marks: {
python: 80,
js: 85,
},
set pythonMarks(mark) {
if(mark <= 100 && mark >= 0 ) {
this.marks.python = mark;
} else {
throw new Error("Please enter python mark between 0 to 100")
}
},
};
Now, whenever user try to set python marks greater than 100 or lower than 0 it will throw error
Click here to read more about Setter
Top comments (0)