Javascript - Defining Multiple Properties

Introduction

To define more than one property on an object, use Object.defineProperties() method.

This method can define multiple properties.

There are two arguments:

  • the object and
  • an object whose property names correspond to the properties' names.
var book = {};

Object.defineProperties(book, {
    _year: {
        value: 2018
    },

    edition: {
        value: 1
  },
  year: {
      get: function(){
          return this._year;
      },

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

This code defines two data properties, _year and edition, and an accessor property called year on the book object.