JavaScript·100 questions

QUESTION: What is Object.defineProperty?

Answer

The Object.defineProperty method in JavaScript is a powerful tool for low-level property management of objects, allowing you to precisely configure their behavior. It defines a new property directly on an object or modifies an existing one, returning the same object. The main feature of the method lies in the ability to use descriptors—special configuration objects that define the hidden characteristics of a property.

There are two types of descriptors: data descriptors and accessor descriptors. A data descriptor includes parameters such as value, which defines the property's value, and writable, which controls whether this value can be modified. An accessor descriptor uses getter and set accessor functions instead of value to intercept reading and writing of the property, which is convenient for "on-the-fly" computations or validation.

An important aspect of the method's operation is that by default, all control flags (writable, enumerable, configurable) for new properties created via Object.defineProperty are set to false. This means the property will not be overwritable by default, will not participate in loops like for...in, and cannot be deleted or have its descriptors changed later. To check the current settings of a specific property, you can use the paired method Object.getOwnPropertyDescriptor.

Practical applications of Object.defineProperty include creating immutable constants within objects, hiding utility fields from iteration, or creating dynamic properties computed on every access. For example, you can define a fullName property that automatically compiles from firstName and lastName upon reading, and splits the string back upon writing.

Was this answer helpful?

More questions in this topic

Related questions from other topics