JavaScript
has and deleteProperty traps
Learn to intercept the in operator and delete with has and deleteProperty traps.
The has trap
The has trap runs when the in operator is used. When you write 'port' in proxy, the handler's has method fires and returns true or false.
const handler = {
has(target, prop) {
return prop in target;
}
};
The trap signature is has(target, prop). With it you can hide or extend the existence check for a property. For example, you can ignore some internal keys and make them look inaccessible from the outside.
The deleteProperty trap
The deleteProperty trap runs when you write delete proxy.port. The handler's deleteProperty method intercepts the deletion.
const handler = {
deleteProperty(target, prop) {
delete target[prop];
return true;
}
};
The trap signature is deleteProperty(target, prop). You can log before deletion, prevent some properties from being deleted, or run extra cleanup. Just like the set trap, it must return true.
Exercise Write has and deleteProperty traps
Define an object named config with host and port properties. Inside a handler, write the has and deleteProperty traps: has returns prop in target, deleteProperty runs delete target[prop] and returns true. Create a proxy variable with new Proxy(config, handler). Log console.log('port' in proxy), run delete proxy.port, then log console.log('port' in proxy) again.
Show example solution
const config = { host: 'localhost', port: 3000 };
const handler = {
has(target, prop) {
return prop in target;
},
deleteProperty(target, prop) {
delete target[prop];
return true;
}
};
const proxy = new Proxy(config, handler);
console.log('port' in proxy);
delete proxy.port;
console.log('port' in proxy);
Test yourself
-
Which trap does 'port' in proxy trigger?
Show answer
has — Correct! The in operator triggers the has trap, which intercepts the existence check.
-
Delete inside deleteProperty
deleteProperty(target, prop) {
delete ____;
return true;
}
Show answer
deleteProperty(target, prop) {
delete target[prop];
return true;
}
-
Match the has and deleteProperty concepts
- has trap
- intercepts in operator
- deleteProperty
- intercepts delete
- in
- existence check
- delete
- property removal
Next lesson: The Reflect API