I know how getter and setter work in JavaScript. What I don't understand is why we need them when we can get the same result using normal functions? Consider the following code:
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(person.fullName); // Jimmy Smith
We can easily replace getter with a function:
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(person.fullName()); // Jimmy Smith
I don't see the point of writing getter and setter.