The handler.deleteProperty() method is a trap for the [[Delete]] object internal method, which is used by operations such as the delete operator.
const monster = {
texture: "scaly",
};
const handler = {
deleteProperty(target, prop) {
if (prop in target) {
delete target[prop];
console.log(`property removed: ${prop}`);
// Expected output: "property removed: texture"
}
},
};
console.log(monster.texture);
// Expected output: "scaly"
const proxy = new Proxy(monster, handler);
delete proxy.texture;
console.log(monster.texture);
// Expected output: undefinednew Proxy(target, {
deleteProperty(target, property) {
}
})The following parameters are passed to the deleteProperty() method. this is bound to the handler.
targetThe target object.
propertyA string or Symbol representing the property name.
The deleteProperty() method must return a Boolean indicating whether or not the property has been successfully deleted. Other values are coerced to booleans.
Many operations, including the delete operator when in strict mode, throw a TypeError if the [[Delete]] internal method returns false.
This trap can intercept these operations:
delete operator: delete proxy[foo] and delete proxy.fooReflect.deleteProperty()Or any other operation that invokes the [[Delete]] internal method.
The proxy's [[Delete]] internal method throws a TypeError if the handler definition violates one of the following invariants:
Reflect.getOwnPropertyDescriptor() returns configurable: false for the property on target, then the trap must return a falsy value.Reflect.isExtensible() returns false on target, and Reflect.getOwnPropertyDescriptor() returns a property descriptor for the property on target, then the trap must return a falsy value.The following code traps the delete operator.
const p = new Proxy(
{},
{
deleteProperty(target, prop) {
if (!(prop in target)) {
console.log(`property not found: ${prop}`);
return false;
}
delete target[prop];
console.log(`property removed: ${prop}`);
return true;
},
},
);
p.a = 10;
console.log("a" in p); // true
const result1 = delete p.a; // "property removed: a"
console.log(result1); // true
console.log("a" in p); // false
const result2 = delete p.a; // "property not found: a"
console.log(result2); // false