Have you ever logged out the contents of an object in 47 different places in your code, trying to see where
object.foo got changed from
'baz'? I know I have!
The good news is, there's a better way!
How it works
The proxy object takes two arguments. 1: the
target, which is the object we want to inspect. 2: the
handler which is a collection of
traps. The supported traps include
set, which intercepts behavior to change a property on the object,
get, which intercepts access of a property,
apply which will intercept function calls, and others. (The documentation linked below lists them all)
Common uses of
Proxy include tracking access, validating changes, extending constructors, modifying access, and more. This gist provides a very simple method of tracking when a property on the object is changed--it uses the
set trap and logs the prop to be changed, the value it's being changed to, and the object that's being changed before forwarding the change back to the object.
- If an object is cloned, you'll lose your proxy and won't have visibility going forward. This might come up often in codebases that emphasize immutability.
- Introduced with ES6, so not as helpful on older codebases.
- (from @snapwich) Requires being able to replace the object reference with a
Proxyobject, which is not always possible.