In JavaScript, Object.defineProperty() is a method used to define a new property directly on an object or modify an existing property on an object. It provides fine-grained control over property attributes such as value, writable, enumerable, and configurable.
Syntax:
Object.defineProperty(object, propertyKey, descriptor)
Parameters:
object : The object on which to define or modify the property.
propertyKey : The name of the property to be defined or modified.
descriptor : An object that specifies the attributes of the property being defined or modified.
Example: Here, Object.defineProperty() is used to define a new property named 'name' on the obj object with the value 'John' . The descriptor object specifies that the property is writable, enumerable, and configurable.
Javascript
const obj = {};
Object.defineProperty(obj, 'name' , {
value: 'GFG' ,
writable: true ,
enumerable: true ,
configurable: true
});
console.log(obj.name);
|
|