liveBook · Manning

Getter

As explained in Secrets of the JavaScript Ninja, Third Edition

A getter is an object or class property accessor that computes and returns a value when the property is read.

A getter lets a property read run a method and return its result. This keeps an API’s surface simple—read `ninjaCollection.firstNinja` like a value—while allowing the value to be computed or other actions to run. section 9.1.1

An ordinary method named `getFirstNinja` is only a getter by convention; the name changes nothing about how it works. A true getter uses `get` in an object literal or class definition. Reading the property invokes it, without parentheses. A paired setter runs when that property is assigned. section 9.1.1

Listing 9.1 Defining getters and setters in an object literal
const ninjaCollection = {
  ninjas: ["Yoshi", "Kuma", "Hattori"],
  get firstNinja() { #A
    console.log(`Getting firstNinja: ${this.ninjas[0]}`); #A
    return this.ninjas[0]; #A
  }, #A
  set firstNinja(newNinja: string) { #B
    console.log(`Setting firstNinja: ${newNinja}`); #B
    this.ninjas[0] = newNinja; #B
  }, #B
};

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

ninjaCollection.firstNinja = "Hachi"; #D

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

The getter returns the first ninja when `firstNinja` is read; the example also shows a setter updating the underlying array when the property is assigned. section 9.1.1

Use `Object.defineProperty` to add an accessor to an object that already exists. It is more verbose than defining `get` in an object literal, but supports dynamic changes, such as overriding a value in a simulated DOM during testing. section 9.1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines accessor syntax, explains read and write invocation, and introduces Object.defineProperty without detailing runtime internals.
Examples
Uses a ninja collection whose firstNinja getter reads an array element and whose setter replaces it.
What it assumes
Builds from ordinary object-property reads and assignments before introducing accessor syntax.
What you can do after
Apply it via object-literal getter syntax or Object.defineProperty to expose values through property reads.
How it connects
Connects getters to setters, object literals, classes, Object.defineProperty, and method invocation.

Also explained in

Compare how 2 books explain getter →

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.