Search code examples
javascriptes6-proxy

Can a Proxy trap assignment to a variable referring to it?


Consider the following Proxy object:

let proxy = new Proxy({}, handler);

If I perform the following assignment, the proxy instance will be overwriten, losing the trap handlers:

proxy = {};

Alright, but if I perform the assignment using Object.assign, it keeps being the same instance (retaining the trap handlers):

Object.assign({}, proxy);

But doing it this way, none of the proxy traps get triggered.

Is it possible to make the proxy trap any of those assignment methods (using either = or Object.assign?


Solution

  • No, it is not possible to trap a reassignment of the variable holding the proxy.

    As for using Object.assign with a proxy, that will usually trigger some traps, either set (for properties being copied from the source to the proxy target) or ownKeys (if the proxy is used as a source). Only if you assign nothing to the proxy (Object.assign(proxy) or Object.assign(proxy, {})), then nothing happens.

    There is no syntax (with a single respective trap) to modify the proxy with multiple property updates. What you may actually be looking for is a normal method, such as proxy.reset({}).