liveBook · Manning

Get/set trap

As explained in Secrets of the JavaScript Ninja, Second Edition

A collective term for Proxy traps that intercept property reads and writes.

A get/set trap is a Proxy handler that intercepts property reads or writes made through the proxy. The matching trap runs implicitly when that access occurs. section 8.2

Listing 8.7. Creating proxies with the Proxy constructor
const emperor = { name: "Komei" };                           #A
const representative = new Proxy(emperor, {                  #B
  get: (target, key) => {                                    #C
    report("Reading " + key + " through a proxy");           #C
    return key in target ? target[key]                       #C
                         : "Don't bother the emperor!"       #C
  },                                                         #C
  set: (target, key, value) => {                             #C
    report("Writing " + key + " through a proxy");           #C
    target[key] = value;                                     #C
  }                                                          #C
});

assert(emperor.name === "Komei", "The emperor's name is Komei");  #D
assert(representative.name === "Komei",                           #D
      "We can get the name property through a proxy");            #D

assert(emperor.nickname === undefined,                            #E
      "The emperor doesn’t have a nickname ");                    #E
assert(representative.nickname === "Don't bother the emperor!",   #F
      "The proxy jumps in when we make inproper requests");       #F

representative.nickname = "Tenno";                                #G
assert(emperor.nickname === "Tenno",                              #G
      "The emperor now has a nickname");                          #G
assert(representative.nickname === "Tenno",                       #G
      "The nickname is also accessible through the proxy");       #G

The emperor example logs reads and writes, returns a warning for missing properties, and forwards assignments to the target object. section 8.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines get and set handlers, traces implicit activation, and demonstrates fallback reads and forwarded writes without exploring broader trap behavior.
Examples
Uses an emperor proxy to read a name, handle a missing nickname, log access, and forward assignments.
What you can do after
Apply JavaScript's Proxy constructor to log reads and writes, return fallback text for missing properties, and forward assignments.
How it connects
Connects JavaScript Proxy traps to property access, target objects, and getter/setter behavior.

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.