JS: Reflect.defineProperty

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Reflect.defineProperty(obj, key, descriptor)

descriptor is Property Descriptor.

🟒 TIP: This is a better version of Object.defineProperty. Because it returns success status.

// create a property that's not enumerable

const jj = {};

const yy = Reflect.defineProperty(jj, "kk", {
 value: 3,
 writable: true,
 enumerable: false,
 configurable: true,
});

console.assert(jj.kk === 3);

console.assert(Reflect.getOwnPropertyDescriptor(jj, "kk").enumerable === false);

// return value is boolean
console.assert(yy === true);

Example. Make a property read-only

/*
make a property read-only
*/

const jj = { "pp": 3 };
Reflect.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 xget
Reflect.defineProperty(
 jj,
 "xget",
 {
  get: function () {
   return "getter called";
  },
 },
);

console.assert(jj.xget === "getter called");

Example. Define Setter Property

const jj = { pp: 3 };

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

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

JavaScript. Define Properties and attributes.