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 'bar'
to 'baz'
? I know I have!
The good news is, there's a better way!
The Proxy
object is a way to intercept or 'trap' fundamental behavior on javascript objects, providing an entry point into that action to inspect or even redefine that behavior.
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
- 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
Proxy
object, which is not always possible.