get and set traps
Learn to intercept property read and write with get and set traps.
The get trap
The get trap runs whenever a property is read. When you write proxy.name, the handler's get method fires and its return value is handed back to you.
const handler = {
get(target, prop) {
return target[prop];
}
};The trap signature is get(target, prop, receiver). Here target is the wrapped object, prop is the property name being read, and receiver is the Proxy itself. You can return any value, so reads can be hidden or transformed.
The set trap
The set trap runs whenever a property is assigned. When you write proxy.age = 28, the handler's set method fires.
const handler = {
set(target, prop, value) {
target[prop] = value;
return true;
}
};The trap signature is set(target, prop, value, receiver). The value is the new value being assigned. A set trap must return true; otherwise the assignment fails in strict mode. You can validate, transform, or reject the value from here.
Exercise Write get and set traps
Define an object named user with a name property. Inside a handler, write the get and set traps: get returns target[prop], set runs target[prop] = value and returns true. Create a proxy variable with new Proxy(user, handler). Assign proxy.age = 28 and log it with console.log(proxy.age).
Show example solution
const user = { name: 'Ayşe' };
const handler = {
get(target, prop) {
return target[prop];
},
set(target, prop, value) {
target[prop] = value;
return true;
}
};
const proxy = new Proxy(user, handler);
proxy.age = 28;
console.log(proxy.age);
Test yourself
-
Return the value inside the get trap
get(target, prop) { return ____; }Show answer
get(target, prop) { return target[prop]; } -
How many parameters does the get trap take?
- target, prop and receiver
- only target
- only prop
- target and value
Show answer
target, prop and receiver — Correct! The get trap takes three parameters: target, prop and receiver.
-
Match the get and set trap concepts
- get trap
- intercepts read
- set trap
- intercepts write
- target
- original object
- value
- new value