JavaScript(JS) object method - defineProperty
In JavaScript, the Object.defineProperty()
method is used to define a new property or modify an existing property on an object. This method allows you to control various aspects of a property, such as its value, whether it is writable, enumerable, or configurable.
The syntax for Object.defineProperty()
is as follows:
Object.defineProperty(obj, prop, descriptor)Source:wwfigi.wtidea.com
Where obj
is the object on which to define the property, prop
is the name of the property, and descriptor
is an object that describes the property. The descriptor
object can contain the following properties:
value
: The value of the property. Defaults toundefined
.writable
: Whether the property can be changed. Defaults tofalse
.enumerable
: Whether the property can be enumerated. Defaults tofalse
.configurable
: Whether the property can be deleted or its attributes can be changed. Defaults tofalse
.get
: A function to get the value of the property.set
: A function to set the value of the property.
Here's an example of using Object.defineProperty()
to define a new property:
const person = {}; Object.defineProperty(person, 'name', { value: 'John', writable: false, enumerable: true, configurable: true }); console.log(person.name); // Output: John
In this example, we define a new property called name
on the person
object, and we set its value to 'John'
. We also set writable
to false
, which means that the property cannot be changed. Finally, we set enumerable
to true
, which means that the property can be enumerated.