Javascript Object define defineProperties()

Introduction

Javascript provides the Object.defineProperties() method to create multiple properties at a time.

This method allows you to define multiple properties using descriptors at once.

There are two arguments:

  • object to define
  • object descriptor

For example:

let book = {};/*from  ww w  . ja  v a  2 s .  c om*/
Object.defineProperties(book, {
    year_: {
        value: 2020
    },

    edition: {
        value: 1
    },

    year: {
        get() {
            return this.year_;
        },

        set(newValue) {
            if (newValue > 2020) {
                this.year_ = newValue;
                this.edition += newValue - 2020;
            }
        }
    }
});

This code defines two data properties, year_ and edition.

It creates an accessor property called year on the book object.




PreviousNext

Related