Proxy object wraps another object and acts as a middleman.
A proxy is created using the
new Proxy constructor with two required arguments: the target and the handler.
let proxy = new Proxy(target, handler)
target— The object we wrap.
handler— An object that defines the methods (also called traps) to control the behaviors of the target.
Proxy creates an undetectable barrier around the target object that redirects all operations to the handler object. If we send in an empty
handler, the proxy is just an empty wrapper around the original object.
To give the proxy meaning, we need to add some functionality to the handler.
Whenever you interact with an object, you are calling an internal method. Proxies allow you to intercept the execution of a given internal method with traps.
So when we run
[[GET]] method to retrieve the
When we run
proxyUser.name the get trap calls the
get() function defined in the
handler to execute before sending the call through to the original object.
get() method has two required parameters:
target— Object passed to the proxy.
property— Name of the accessed property.
To customize the proxy, we define functions on the
handler object. Here we define the
get method to log the access:
To let the call through, we return
Now, if we create a proxy with this handler and try to access the original object, we log the call:
We can see that when we access a property of the
user object via the
proxyUser object, the
get() method fires in the
The set trap controls behavior when a property of the
target object is assigned.
Let’s validate the input of the
If we try to assign a wrong type to `age` an error is thrown:
proxyUser.age = ‘old’;
// -> TypeError: Age is just a number.
In the line
target[property] = value we set the
age property of the
set() method should return a boolean value
Uncaught TypeError: ‘set’ on proxy: trap returned falsish for property ‘age’
In addition to intercepting reads and modifications to properties, Proxy can intercept a total of 13 operations.
We have learned how we can use a proxy to spy on objects. You should now be able to add behaviors to them by using trap methods in the handler object. We have only dipped our toes into proxies with a couple of basic examples but it’s enough to get started and inspired to explore the possibilities!
Getting Started Series