Proxy & Reflect
The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object. (MDN)
A Proxy object wraps another object and intercepts operations, like reading/writing properties and others, optionally handling them on its own, or transparently allowing the object to handle them. (https://javascript.info/proxy)
Proxies
A Proxy in Javascript is an object that wraps another object and intercepts (or ‘traps’) the incoming operations, allowing us to change their default behaviour.
This kind of technique is called “Metaprogramming”, which is a term for a program that can treat other programs as their data.
Creating a Proxy
The Proxy
constructor accepts two arguments Proxy(target: Object, handler)
target
– the object you want to wrap. This can be any kind of JS object, including functions.handler
– this is the configuration object for the proxy. Here you define the “trap” methods used to intercept certain operations. Ieget
set
etc…
// The object we want to proxy
const obj = { fruit: 'apple' }
// The handler object (empty for now)
const handlers = {}
// Init a new Proxy
const proxy = new Proxy(obj, handlers)
Now we can access the proxy
object, just like we can with obj
.
obj.fruit // 'apple'
proxy.fruit // 'apple'
Because we aren’t defining any handlers in the handlers
object, the proxy will just perform the default functionality for the requested operation, which in this case is the get
.
Handlers
If we want to change the default behaviour of the proxied object we can do so by setting a trap
in the handlers
object.
Traps are methods that provide access to the object in a certain way.
const obj = { fruit: 'apple' }
const handlers = {
get() {
return 'orange'
}
}
const proxy = new Proxy(obj, handlers)
By doing this we’re telling the proxy to change the way it handles the get
operation.
obj.fruit // 'apple'
proxy.fruit // 'orange'
Note that we aren’t changing the contents of our object, just what is returned when attempting to access it.
obj // { fruit: 'apple' }
proxy // { fruit: 'apple' }
Complete list of available traps:
Examples:
- Object observer (pubsub)
- Array negative index
- Validation
- Suggested properties
- Function spying
- Typed objects
Notes
Trap — Similar to traps in operating systems, traps in this context are methods that provide access to the object in a certain way (https://blog.logrocket.com/practical-use-cases-for-javascript-es6-proxies/)
Resources
Practical use cases for JavaScript ES6 proxies - LogRocket Blog