Object.defineProperty for Dynamic Getters/Setters
You'll learn how to add getters and setters to objects after they're created, or with fine-grained control over property behavior.
Why Use Object.defineProperty?
So far you've defined getters and setters directly inside object literals using the get and set keywords. But what if you need to add them to an existing object? Or what if you want more control over whether the property is enumerable or configurable? That's where Object.defineProperty comes in.
The Core Idea
Object.defineProperty lets you define or modify a single property on an object with full control over its descriptor. For getters and setters, you pass get and set functions inside the descriptor object:
const person = { firstName: 'John', lastName: 'Doe' };
Object.defineProperty(person, 'fullName', {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
},
enumerable: true,
configurable: true
});
console.log(person.fullName); // "John Doe"
person.fullName = 'Jane Smith';
console.log(person.firstName); // "Jane"
When Is This Useful?
This approach is powerful when you're:
- Adding properties to objects dynamically at runtime
- Building libraries where you need precise control over property attributes
- Working with existing objects you can't modify at creation time
Think of it like installing a new control panel on existing machinery—you're retrofitting the object with smart property behavior after the fact.
Key Takeaway: Object.defineProperty lets you add getters and setters to objects dynamically, with full control over enumerability and configurability—perfect for runtime property management.