I don’t quite understand the purpose of using Getters and Setters.
I think I understand how they work but don’t really understand how they differ from creating a ‘normal’ method that updates an objects property.
The lesson on getters provides the following benefits but are these not the same when using a normal method?
Now that we’ve gone over syntax, let’s discuss some notable advantages of using getter methods:
- Getters can perform an action on the data when getting a property.
- Getters can return different values using conditionals.
- In a getter, we can access the properties of the calling object using
this
.
- The functionality of our code is easier for other developers to understand.
For example, this code does exactly what I want. Using a getter only allows me to envoke the method without the parenthesis right?
const person = {
firstName: 'David',
lastName: 'Smith',
fullName() {
if (this.firstName && this.lastName) {
return `${this.firstName} ${this.lastName}`;
} else {
return `Error: firstname and lastname not available`;
}
},
age: 34,
};
console.log(person.fullName()); // Returns 'David Smith'
// CODE ABOVE DOES WHAT THE CODE BELOW DOES, RIGHT? WHAT IS THE BENEFIT OF THE BELOW?
const person = {
firstName: 'David',
lastName: 'Smith',
get fullName() {
if (this.firstName && this.lastName) {
return `${this.firstName} ${this.lastName}`;
} else {
return `Error: firstname and lastname not available`;
}
},
age: 34,
};
console.log(person.fullName); // Still Returns 'David Smith'