Setters & Getters
JavaScript has a special syntax for making getter methods
class Person { constructor(first, last) { this.first = first; this.last = last; } get fullName() { return `${this.first} ${this.last}`; } } const teacher = new Person('Ali', 'Madooei'); console.log(teacher.fullName);
- A getter method is a method with no parameters, declared with the keyword
get
. - It can also be used in object literal.
- Call getters without parentheses!
- Think of a getter as a dynamically computed property.
Likewise, there is a special syntax for setter methods.
class Person { get firstName() { return this.first; } get lastName() { return this.last; } set fullName(value) { const parts = value.split(" "); this.first = parts[0]; this.last = parts[1]; } } const teacher = new Person(); teacher.fullName = "Ali Madooei"; console.log(teacher.lastName);
- A setter method is a method with one parameter, declared with the keyword
set
. - It can also be used in object literal.
- Setters are invoked through assignment to property.
Getters/setters look like fields, act like methods.
I don't see a great value in having a special setter and getter method! In particular, since properties can not be made private, it seems redundant to use setters/getters.