liveBook · Manning

Accessor descriptor

As explained in Secrets of the JavaScript Ninja, Third Edition

An object property whose value is accessed through getter or setter behavior rather than a directly stored value.

An accessor descriptor defines a property whose getter or setter runs when the property is read or assigned. Use Object.defineProperty to add one, or use getter and setter syntax in object literals and ES6 classes. section 9.1.2 section 9.5

Watch how the descriptor’s options and methods affect property behavior:

  • A getter without a setter makes the property read-only; assigning to it throws in strict mode and fails silently otherwise. section 9.1.2
  • A setter without a getter allows assignments, but reading the property returns undefined. section 9.1.2
  • enumerable defaults to false; configurable also defaults to false, preventing redefinition or deletion. Set configurable to true to allow those changes. 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 property makes firstNinja behave like a view of ninjas[0]: reading it calls the getter, and assigning to it calls the setter. section 9.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains getter and setter behavior, descriptor defaults, and assignment or deletion effects.
Examples
Demonstrates a firstNinja property that reads from and writes to an array, plus read-only and write-only properties.
What you can do after
Apply accessor behavior with Object.defineProperty or getter and setter syntax.
How it connects
Connects to Object.defineProperty, getters, setters, and data descriptors.

Also explained in

Compare how 2 books explain accessor 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.