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 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.
- JS: Property Attributes
- JS: Enumerable Property
- JS: Property Descriptor
- JS: Object.create
- JS: Object.defineProperty β
- JS: Reflect.defineProperty
- JS: Object.defineProperties
- JS: Object.prototype.propertyIsEnumerable β
- JS: Object.getOwnPropertyDescriptor β
- JS: Reflect.getOwnPropertyDescriptor
- JS: Object.getOwnPropertyDescriptors