Javascript - Class Accessor Properties

Introduction

Accessor properties do not contain a data value.

They contain getter and setter function.

When an accessor property is read from, the getter function is called, and it's the function's responsibility to return a valid value.

When an accessor property is written to, a function is called with the new value, and that function must decide how to react to the data.

Accessor properties have four attributes:

Item Meaning
[[Configurable]]if the property may be redefined by removing the property via delete, changing the property's attributes, or changing the property into a data property. By default, this is true for all properties defined directly on an object.
[[Enumerable]]if the property will be returned in a for-in loop. By default, this is true for all properties defined directly on an object.
[[Get]]The function to call when the property is read from. The default value is undefined.
[[Set]] The function to call when the property is written to. The default value is undefined.

It is not possible to define an accessor property explicitly; you must use Object.defineProperty().

Demo

var book = {
  _year: 2018,//from ww w .  jav  a2 s.  c o m
  edition: 1
};
Object.defineProperty(book, "year", {
    get: function(){
        return this._year;
    },
    set: function(newValue){

        if (newValue > 2018) {
            this._year = newValue;
            this.edition += newValue - 2018;
        }
    }
});

book.year = 2005;
console.log(book.edition);   //2

Result

In this code, an object book is created with two default properties: _year and edition.

The underscore on _year indicates that a property is not intended to be accessed from outside.

The year property is defined to be an accessor property where the getter function simply returns the value of _year and the setter does some calculation to determine the correct edition.

Changing the year property to 2005 results in both _year and edition changing to 2.

It's not necessary to assign both a getter and a setter.

Assigning just a getter means that the property cannot be written to and attempts to do so will be ignored.

In strict mode, trying to write to a property with only a getter throws an error.

A property with only a setter cannot be read and will return the value undefined in nonstrict mode, while doing so throws an error in strict mode.