The Object.defineProperty()
method in JavaScript allows you to define or modify a property directly on an object and control the property's behaviour. It provides fine-grained control over the properties of objects, including whether they are writable, enumerable, or configurable.
Syntax
Object.defineProperty(obj, prop, descriptor);
-
obj:
The object on which to define the property. -
prop:
The name of the property to be defined or modified. -
descriptor:
An object that describes the property being defined or modified.
Property Descriptors
A property descriptor is an object that can contain the following keys:
-
value
: The value associated with the property (data descriptor). -
writable
: Boolean indicating if the property value can be changed. -
configurable
: Boolean indicating if the property can be deleted or changed. -
enumerable
: Boolean indicating if the property will be listed during enumeration of the properties (like in a for...in loop).
Examples
Basic Example
Let's create an object and define a new property on it using Object.defineProperty()
.
const person = {};
// Define a property 'name' on the person object
Object.defineProperty(person, 'name', {
value: 'Alice',
writable: true,
enumerable: true,
configurable: true
});
console.log(person.name); // Output: Alice
Making a Property Read-Only
You can use Object.defineProperty()
to make a property read-only by setting writable
to false
.
Object.defineProperty(person, 'age', {
value: 30,
writable: false,
enumerable: true,
configurable: true
});
console.log(person.age); // Output: 30
person.age = 25; // This will not change the value of age
console.log(person.age); // Output: 30
Making a Property Non-Enumerable
You can make a property non-enumerable by setting enumerable
to false
.
Object.defineProperty(person, 'gender', {
value: 'female',
writable: true,
enumerable: false,
configurable: true
});
console.log(person.gender); // Output: female
for (let key in person) {
console.log(key); // Output: name, age (gender is not listed)
}
Summary
Object.defineProperty()
gives you detailed control over the properties of an object. You can control whether a property is writable, enumerable, configurable, and even define custom getters and setters. This makes it a powerful tool for creating complex and well-encapsulated objects in JavaScript.
Top comments (0)