Jump to Categories

Getters & Setters

Making use of the get and set keywords in JS. They are followed by the property they relate to (personDetails).

These two keywords define accessor functions: a getter and a setter for the personDetails property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set.

const person = {
  name: 'John',
  get personDetails() {
    return 'Hello' + this.name;
  },
  set personDetails(name) {
    this.name = name;
  } 
}

person.personDetails = 'Paul';
console.log(person.personDetails);

ES6

ES6 classes brings a new syntax for getters and setters on object properties

Refs