Javascript - Class Accessor Properties

Introduction

ES6 classes allow you to create accessor properties on the prototype.

We can use get and set keywords before the identifiers to create getter and setter properties respectively.

These property descriptors are non-enumerable and can be accessed using Object.getOwnPropertyDescriptor() on the class's prototype, since these properties reside on the prototype object.

Demo

class Bus { 
        constructor(model, capacity) { 
                this._model = model; //from  w  w w  . ja va 2 s  .  co  m
                this._capacity = capacity; 
        } 

        get model() { 
                return this._model; 
        } 

        get capacity() { 
                return this._capacity; 
        } 

        set model(model) { 
                this._model = model; 
        } 

        set capacity(capacity) { 
                this._capacity = capacity; 
        } 
} 
const jet = new Bus("Jet", 100); 
console.log(jet.capacity); 
console.log(Object.getOwnPropertyDescriptor(Bus.prototype, "model"));

Result

Here, we have added an _ (underscore) before property names inside the class definition.

You must never have your setter method name the same as that of your property.