liveBook · Manning

Property descriptor

As explained in Secrets of the JavaScript Ninja, Third Edition

A property descriptor is an object that specifies the attributes used to define a JavaScript property.

A property descriptor is an options object passed to Object.defineProperty to specify a property's attributes. Descriptors can control enumeration and define accessors that run getters or setters when the property is read or written. section 9.1.2

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

This descriptor makes firstNinja enumerable and uses a getter and setter to read and update the first item in ninjas. section 9.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains enumerability and accessor descriptors with examples, without detailing every descriptor attribute.
Examples
Uses a getter and setter for firstNinja and a getter-only randomNumber property that rejects writes.
What you can do after
Apply Object.defineProperty to control property enumeration and define getter or setter behavior.
How it connects
Connects property descriptors to Object.defineProperty, enumerability, getters, setters, and symbol-keyed properties.

Also explained in

Compare how 3 books explain property descriptor →

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.