Getters and setters

Earlier, to add accessor properties to objects we had to use the Object. defineProperty() method. From ES6 onwards, there are get and set prefixes for methods. These methods can be added to object literals and classes to define the get and set attributes of the accessor properties.

When get and set methods are used in a class body, they are added to the prototype property of the class.

Here is an example to demonstrate how to define the get and set methods in a class:

class Person {     constructor(name) {         this._name_ = name;     }     get name() {         return this._name_;     }     set name(name) {        this.someOtherCustomProp = true;        this._name_ = name;     } } const p = new Person("Eden"); console.log(p.name); // Outputs: "Eden"p.name = "John"; ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.