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 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 = "Ali Madooei";

console.log(teacher.fullname);
  • A setter method is a method with one parameter, declared with 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 methods. In particular since properties can not be made private, it seems redundant to use setters/getters.