Javascript Object Accessor Property

Introduction

Javascript accessor properties do not contain a data value.

They contain a combination of a getter function and a setter function.

When an accessor property is read from, the getter function is called.

The function should return a valid value.

When an accessor property is written to, a function is called with the new value.

That function must decide how to react to the data.

Accessor properties have four attributes:

Attribute Default Value Meaning
[[Configurable]] true Indicates 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.
[[Enumerable]] true Indicates if the property will be returned in a for-in loop.
[[Get]] undefinedThe function to call when the property is read from.
[[Set]] undefined The function to call when the property is written to.

To define an accessor property explicitly, use Object.defineProperty().

Here's a simple example, P:It defines object with pseudo-private member 'year_' and public member 'edition'

let book = {//from  w w w . j  a v a 2 s  .c o m
    year_: 2020,
    edition: 1
};

Object.defineProperty(book, "year", {
    get() {
        return this.year_;
    },
    set(newValue) {
        if (newValue > 2020) {
            this.year_ = newValue;
            this.edition += newValue - 2020;
        }
    }
});
book.year = 2018;
console.log(book.edition); // 2 

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 returns the value of year_.

The setter does some calculation to determine the correct edition.

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 non-strict mode, while doing so throws an error in strict mode.




PreviousNext

Related