Setter and Getter Methods

There is 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);  // Ali Madooei
  • A getter method is a method with no parameters, declared with the keyword get.
  • It can also be used in an object literal.
  • Call getters without parentheses.
  • Think of a getter as a dynamically computed property.

There is a similar 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);  // Madooei
  • A setter method is a method with one parameter, declared with the keyword set.
  • It can also be used in an object literal.
  • Setters are invoked through assignment to a property.