liveBook · Manning

Getter

As explained in Secrets of the JavaScript Ninja, Second Edition

A pair of property accessors that execute custom code when a property is read or assigned.

Need to log a property read or keep a displayed value current? A getter lets ordinary property access run code. Its companion, a setter, runs when a value is assigned. Unlike explicit methods such as getSkillLevel() and setSkillLevel(), accessors let callers keep using familiar expressions such as object.skillLevel and object.skillLevel = 20. section 8.1 section 8.1.1

Define a getter by placing get before a property name in an object literal or ES6 class. Reading that property calls the getter and yields its return value; assigning to a matching setter calls the setter with the assigned value. The two can log access, validate writes, or trigger other side effects without requiring callers to invoke methods explicitly. section 8.1.1 section 8.1

Listing 8.2. Defining getters and setters in object literals
const ninjaCollection = {
  ninjas: ["Yoshi", "Kuma", "Hattori"],
  get firstNinja(){                              #A
    report("Getting firstNinja");                #A
    return this.ninjas[0];                       #A
  },                                             #A
  set firstNinja(value){                         #B 
    report("Setting firstNinja");                #B
    this.ninjas[0] = value;                      #B
  }                                              #B
};

assert(ninjaCollection.firstNinja === "Yoshi",   #C
       "Yoshi is the first ninja");              #C

ninjaCollection.firstNinja = "Hachi";            #D

assert(ninjaCollection.firstNinja === "Hachi"    #E
    && ninjaCollection.ninjas[0] ===  "Hachi",   #E
       "Now Hachi is the first ninja");          #E

The firstNinja accessor makes reading and replacing the first array entry look like ordinary property access while logging both operations. section 8.1.1

Object.defineProperty offers another way to install accessors: supply get and set functions in a property descriptor. An accessor descriptor cannot combine get or set with the data-property keys value and writable. A closure can hold the underlying value so it is reached through the accessor rather than through a public value property. section 8.1.1 section 7.3.1

A value calculated on demand

A fullTitle getter can return this.name + " " + this.clan rather than store a separate title. Its setter can split an assigned title and update name and clan. Use this property form when the value depends on the object’s state and reads naturally as data; an explicit getFullTitle() method remains an option. section 8.1.3

Accessors control particular properties. If the goal is to log reads and writes across an object, adding logging to each accessor mixes that concern into property code and risks missing new properties. A Proxy with get and set traps can handle those interactions in one place. section 8.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Works through implicit invocation, object-literal and class syntax, and Object.defineProperty descriptors; stops at property-level control before turning to proxies.
Examples
Uses an array’s first-item accessor, a closure-backed skill level, and a title computed from name and clan.
What it assumes
Assumes familiarity with JavaScript objects and property access, while revisiting closure-backed private values through an explicit-method example.
What you can do after
Build it from scratch using object-literal, class, or Object.defineProperty accessors to control or compute a property’s value.
How it connects
Connects property descriptors and closures to computed properties, and contrasts per-property accessors with Proxy get and set traps.

Related concepts

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