JS: Object.defineProperty

By Xah Lee. Date: . Last updated: .

Object.defineProperty

Object.defineProperty(obj, key, descriptor)
Create or modify Property Attributes of a single property by Property Descriptor.
Return the modified object.

Example: Create a Property That's Not Enumerable

/*
create a property that's not enumerable
*/

const xx = {};

Object.defineProperty(xx, "pp", {
  value: 3,
  writable: true,
  enumerable: false,
  configurable: true,
});

console.log(xx.pp === 3);

Example: Make a property read-only

/*
make a property read-only
*/

const jj = { "pp": 3 };
Object.defineProperty(jj, "pp", { writable: false });

Note: once a property's “writable” attribute is set false, it can't be set back to true.

Example: Define Getter Property

const jj = { pp: 3 };

// add a getter property key "gg"
Object.defineProperty(
  jj,
  "gg",
  {
    get: function () {
      return "getter called";
    },
  },
);

console.log(jj.gg === "getter called");

Example: Define Setter Property

const jj = { pp: 3 };

// add a setter property key "ss"
Object.defineProperty(
  jj,
  "ss",
  {
    set: function (x) {
      console.log("setter called with arg " + x);
    },
  },
);

jj.ss = 4;
// prints: setter called with arg 4

JavaScript, Define Properties

BUY ΣJS JavaScript in Depth