The static function Reflect.defineProperty provides the ability to accurately add or alter a property of an object. This method returns a Boolean value that signifies whether the property was defined successfully or not.
Syntax
Reflect.defineProperty(target, propertyKey, attributes)
Parameter
target: This refers to the object that specifies the property.
propertyKey: This refers to the identifier of the property that is intended to be established or altered.
Attributes: These refer to the characteristics associated with the property that is either being defined or altered.
Return value:
This approach yields a Boolean result that signifies whether the property has been successfully established or not.
Exceptions
A TypeError will be raised by this exception if the specified target is not classified as an Object.
Example 1
const u = {};
const result = Reflect.defineProperty(u, "p",
{ value : 6,});
console.log( u );
Output:
Object { }
Example 2
const u = {};
const su = Reflect.defineProperty(u, "p",
{ value : 3,
writable: true,
//write
// enumerable: true,
//configurable: true
}
);
console.log( u );
console.log( su);
Output:
Object { }
true
Example 3
const object1 = {};
const object2 = {};
(Reflect.defineProperty(object2, 'property2', {value: 12}))
if (Reflect.defineProperty(object1, 'property1', {value: 42})) {
console.log('property1 created!');
} else {
console.log('problem creating property1');
}
console.log(object1.property1);
console.log(object2.property2);
Output:
"property1 created!"
42
12