JS: Reflect.defineProperty
(new in ECMAScript 2015)
Reflect.defineProperty(obj, key, descriptor)-
- Create or modify a property's Property Attributes.
- Return
trueif successful, elsefalse.
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 result = Reflect.defineProperty(jj, "dog", { value: 3, writable: true, enumerable: false, configurable: true, }); console.log(jj.dog); // 3 console.log( Reflect.getOwnPropertyDescriptor(jj, "dog").enumerable === false, ); // true // return value is boolean console.log(result); // true
Example. Make a property read-only
// make a property read-only const jj = { dog: 3 }; Reflect.defineProperty(jj, "dog", { 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 = {}; // 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 = {}; // 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