There is a guard at the office door. Anyone who wants to enter must pass the guard first: the guard writes down their name, checks their card, then lets them in or sends them away.
A Proxy works like that guard, but for an object. The office is the real object, and the visitors are the operations on that object, such as reading or changing a property. A Proxy wraps the object and catches every operation before it reaches the real object. Inside the Proxy you can record the operation, check it, then forward it or refuse it.
A first Proxy: a set trap for validation
This example wraps the object target in a Proxy that only accepts an age that is a number above 0:
const target = { age: 20 }
const student = new Proxy(target, {
set(obj, prop, value) {
if (typeof value !== 'number' || value <= 0) {
throw new Error('Age must be a number above 0')
}
obj[prop] = value
return true
}
})
student.age = 25 // stored
student.age = -5 // Error: Age must be a number above 0
new Proxy(target, handler)makes the Proxy.targetis the real object, andhandleris an object that holds the traps. In this example the handler is written directly as the second argument.- A trap is a method on the handler that catches one kind of operation.
setcatches every write to a property, such asstudent.age = 25. - The
settrap receivesobj(the real object),prop(the property's name, here'age') andvalue(the new value,25). throw new Error(...)refuses the write: the write stops, and the old value stays.obj[prop] = valuestores the value in the real object. Without this line, the value is never stored.return truereports that the write succeeded. Asettrap has to returntruewhen it succeeds. If the trap returns nothing, the operation counts as failed.
The result: student.age becomes 25. The value -5 is refused with an Error because of value <= 0, and the age stays 25. student.age = 'abc' is refused too, because its type isn't number. One note: a Proxy only guards operations that go through it. target.age = -5 writes directly to the real object, so it isn't checked at all.
The get trap: catching reads
This example makes a Proxy that gives its own answer for a property that doesn't exist:
const p = new Proxy({ name: 'Budi' }, {
get(obj, prop) {
return prop in obj ? obj[prop] : 'not found'
}
})
console.log(p.name) // Budi
console.log(p.age) // not found
get(obj, prop)runs every time a property is read.prop in objchecks whether that property exists on the object.- Whatever the trap returns becomes the result of the read.
So a missing property isn't always undefined when it is read through a Proxy. Without this get trap, p.age is undefined. With this trap the result is 'not found', because the trap decides the result.
Reflect: forwarding an operation as it is
Reflect is an object built into JavaScript. Its methods have the same names as the traps, and each method does the built-in operation (what happens when there is no Proxy). This example records every read and write, then forwards it with Reflect:
const handler = {
get(obj, prop) {
console.log(`Reading ${prop}`)
return Reflect.get(obj, prop)
},
set(obj, prop, value) {
console.log(`Writing ${prop} = ${value}`)
return Reflect.set(obj, prop, value)
}
}
const user = new Proxy({}, handler)
user.name = 'Budi' // Writing name = Budi
console.log(user.name) // Reading name, then Budi
Reflect.get(obj, prop)is the same asobj[prop].Reflect.set(obj, prop, value)is the same asobj[prop] = value, and returnstruewhen it succeeds. Soobj[prop] = valueplusreturn truecan be shortened toreturn Reflect.set(obj, prop, value).- In the exercise, your Proxy is checked with
Reflect.set(proxy, 'b', 7). It returns whatever that Proxy'ssettrap returns. If the trap has noreturn true, the result isfalse.
Besides get and set, there are other traps, such as has (for the in operator) and deleteProperty (for delete).
⚠️ set traps that leak, or don't store anything
- A
settrap withoutreturn true. The write is reported as failed. In strict mode, that failure becomes a TypeError. - Forgetting to store the value. A trap that only checks and then does
return truenever puts the value into the object. - Only checking
value < 0. The number 0 is still accepted. If the rule is "above 0", refusevalue <= 0. - Forgetting to check the type.
'abc' <= 0isfalse, so text is accepted too when there is notypeof value !== 'number'.
TL;DR: new Proxy(target, handler) wraps the object target, and the traps (methods on handler) catch the operations on that object. The set(obj, prop, value) trap (the real object, the property's name, the new value) catches writes to a property. Refuse a write with throw new Error(...), or store it with obj[prop] = value and then return true. The get(obj, prop) trap catches reads of a property, and whatever it returns becomes the result of the read. Reflect.get and Reflect.set run the built-in operation (what happens when there is no Proxy), so a trap can forward an operation with return Reflect.set(obj, prop, value).
⚡ A guard in front of an object
Write:
const student = new Proxy(target, {
set(obj, prop, value) {
if (typeof value !== 'number' || value <= 0) {
throw new Error('Age must be a number above 0')
}
obj[prop] = value
return true
}
})
student.age = -5 // Error
Meaning: A Proxy wraps the object target and catches every operation before it reaches that real object, like a guard at an office door. The set trap is a method that catches every write to a property. Here the value -5 is refused. Inside the trap, obj is the real object, prop is the property's name, and value is the new value. throw refuses the write, obj[prop] = value stores the value, and return true reports that the write succeeded.
⚡ A get trap decides the result
Write:
const p = new Proxy({ name: 'Budi' }, {
get(obj, prop) {
return prop in obj ? obj[prop] : 'not found'
}
})
Guess first: what does p.age give?
'not found', not undefined. The object has no age property, so the trap returns 'not found'. Whatever the get trap returns becomes the result of the read.
Meaning: The get(obj, prop) trap runs every time a property is read through the Proxy. prop in obj checks whether that property exists on the real object. Whatever the trap returns becomes the result of the read.
⚡ Reflect forwards it as it is
Write:
set(obj, prop, value) {
console.log(`Writing ${prop} = ${value}`)
return Reflect.set(obj, prop, value)
}
Meaning: This code is the set trap of a Proxy. Reflect.set(obj, prop, value) is the same as obj[prop] = value, and returns true when it succeeds. So a trap can record the write first, then forward the operation in one line.