liveBook · Manning

Object.defineProperty

As explained in Secrets of the JavaScript Ninja, Third Edition

Object.defineProperty is a JavaScript built-in method that creates or modifies an object's property with a specified property descriptor.

Object.defineProperty adds a property to an existing object using a descriptor. It can create getters and setters, or define data properties with specific behavior. section 9.1.1 section 9.1.2

Listing 9.2 Defining getters and setters dynamically
interface NinjaCollection { #A
  ninjas: string[]; #A
  firstNinja: string; #A
} #A
 
const ninjaCollection = { #B
  ninjas: ["Yoshi", "Kuma", "Hattori"], #B
} as NinjaCollection; #B

Object.defineProperty(ninjaCollection, "firstNinja", { #C
  get() { #C
    console.log(`Getting firstNinja: ${this.ninjas[0]}`); #C
    return this.ninjas[0]; #C
  }, #C
  set(newNinja: string) { #C
    console.log(`Setting firstNinja: ${newNinja}`); #C
    this.ninjas[0] = newNinja; #C
  }, #C
}); #C

This defines firstNinja dynamically: reading or assigning the property accesses the first item in ninjas. section 9.1.1

Descriptor options affect how a property behaves:

  • Properties created this way are non-enumerable by default, so common enumeration and copying operations omit them. Set enumerable: true to include them. section 9.1.2
  • A getter-only property can’t be assigned to; a setter-only property accepts values but reads as undefined. section 9.1.2
  • The configurable option allows a property to be deleted; a value descriptor can define a data property. section 9.1.2
// Object from Listing 9.1
Object.keys(ninjaCollection)
> [ 'ninjas', 'firstNinja' ]
 
// Object from Listing 9.2
Object.keys(ninjaCollection)
> [ 'ninjas' ]

Compare Object.keys results to see how a property added with Object.defineProperty differs from one defined in an object literal. section 9.1.2

Use Object.defineProperty when a property must be added after object creation or needs behavior such as validation, logging, or a computed value. Its descriptor syntax is more verbose than object-literal getter and setter syntax. section 9.1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains accessor and data-property descriptors through examples of enumeration, assignment, and deletion behavior.
Examples
Uses a ninjaCollection accessor, a random-number getter, a password-hashing setter, property deletion, and a value property.
What you can do after
Apply it to add accessors or data properties and control their enumeration, writability, or configurability.
How it connects
Connects property descriptors with getters and setters, object enumeration, JSON serialization, symbols, and TypeScript typing.

Also explained in

Compare how 3 books explain Object.defineProperty →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.