SmallTown NE SmallTown NE - 15 days ago 5
Javascript Question

How to delete a property of the object created by Proxy?

proxy = new Proxy({}, {
deleteProperty(target, propKey){
console.log(arguments);

return true;
}
});

proxy.xx = 3;

delete proxy.xx; // log and return true

proxy.xx // 3


Like the code, delete operation does't have effect.

I read the delete operator on MDN:


The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios:



  • If the property which you are trying to delete does not exist, delete will not have any effect and will return true

  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).

  • Any property declared with var cannot be deleted from the global scope or from a function's scope.


    • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).

    • Functions which are part of an object (apart from the global scope) can be deleted with delete.


  • Any property declared with let or const cannot be deleted from the scope within which they were defined.

  • Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().



I think my code doesn't belong to these above, so how to explain it? Thanks.

Answer

If you want to delete a property, you have to call Reflect.deleteProperty(). Just returning true doesn't delete it, it only makes calls to Reflect.deleteProperty() return true:

const proxy1 = new Proxy({}, {
  deleteProperty(target, propKey) {
    return true;
  },
});

proxy1.xx = 3;
// true, because deleteProperty trap returns true.
console.log(Reflect.deleteProperty(proxy1, 'xx'));
// 3, because it wasn't actually deleted.
console.log(proxy1.xx); // 3

const proxy2 = new Proxy({}, {
  deleteProperty(target, propKey) {
    Reflect.deleteProperty(target, propKey);
    return false;
  },
});

proxy2.xx = 3;
// false, because deleteProperty trap returns false.
console.log(Reflect.deleteProperty(proxy2, 'xx'));
// undefined, because it was deleted.
console.log(proxy2.xx);

Comments