A trap is a handler function that runs when a specified interaction passes through a Proxy. Property reads and writes can trigger `get` and `set` traps, letting you customize behavior without adding that logic to each property. section 8.2
Common uses include:
- Intercepting property reads and writes, such as returning a fallback message when a property is missing. section 8.2
- Logging access in one reusable Proxy handler instead of mixing logging into domain code or defining it separately for each property. section 8.2.1
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
See `get` and `set` traps intercept reads and writes through an emperor proxy. section 8.2
Listing 8.9. Using proxies makes it easier to add logging to objects
function makeLoggable(target){ #A
return new Proxy(target, { #B
get: (target, property) => { #C
report("Reading " + property); #C
return target[property]; #C
}, #C
set: (target, property, value) => { #D
report("Writing value " + value + " to " + property); #D
target[property] = value; #D
} #D
});
}
let ninja = { name: "Yoshi"}; #E
ninja = makeLoggable(ninja); #E
assert(ninja.name === "Yoshi", "Our ninja Yoshi"); #F
ninja.weapon = "sword"; #F
See a reusable logging handler applied to a ninja object. section 8.2.1
