What does that mean?
The object whose properties need to be overridden is known as the target. It can be any object we want. This means it could be a regular JS object, or a third-party module, a function, or a proxy itself.
Since there are multiple traps on an object, we can have multiple configurations for a single object. Therefore the proxy configuration is known as a handler. It can have multiple traps. A get trap for reading properties of the target, a set trap for writing them, etc.
If we were to create a proxy without any traps on the handler
The proxy is a transparent wrapper around the target object.
A proxy does not have any properties of its own. Before we start intercepting handlers, let us take a look at when the handler methods are triggered.
get: reading a property
set: writing to a property
has: in operator
deleteProperty: delete operator
apply: function call
construct: new operator
defineProperty: Object.defineProperty, Object.defineProperties
getOwnPropertyDescriptor: Object.getOwnPropertyDescriptor, for..in, Object.keys/values/entries
ownKeys: Object.getOwnPropertyNames, Object.getOwnPropertySymbols, for..in, Object.keys/values/entries
Assigning default values using the GET trap
Let us assign a default value for undefined properties.
The get trap that we have defined overrides the lookup behavior. And if the object has a defined property, we return the value. Else we return our custom message.
Performing validation using the SET trap
Let us create a proxy to validate the age property before setting it.
Private properties using the HAS, OWNKEYS, SET, GET, and DELETE traps
A few gotchas before we conclude the post:
- Currently, there is no support for proxies in IE.
And there are no complete polyfills available 🙁
- There is no way to determine whether an object is a proxy or not.
- Once defined, it is not possible to change the target or the handler objects.
- Proxy performance is relatively slow.
- The target needs to be an object and proxies cannot be applied on primitives.
Let us know your experiences with it, or if you face any issues. What proxies are you going to create? Drop a comment below and let us know.