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('Yinzhi', 'Cao'); 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 fullName() { return `${this.first} ${this.last}`; } set fullName(value) { const parts = value.split(" "); this.first = parts[0]; this.last = parts[1]; } } const teacher = new Person(); teacher.fullname = "Yinzhi Cao"; console.log(teacher.fullname);
- 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.