Proxy
Last updated
Last updated
Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object.
A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.
The Proxy design pattern in JavaScript allows you to intercept and customize operations performed on objects such as property lookup, assignment, enumeration, function invocation, etc.
This pattern provides a way to control access to the target object and enables you to add behaviors to it without modifying its code directly.
In this example:
We have a targetObject
with properties name
and age
.
We create a handler
object with traps for get
and set
operations.
We create a proxy object proxyObject
using new Proxy(targetObject, handler)
.
Whenever we access properties or set properties on proxyObject
, the corresponding traps in the handler
object are invoked.
You can add more traps for different operations like has
(for the in
operator), deleteProperty
(for the delete
operator), apply
(for function invocation), etc., depending on your requirements.
The Proxy pattern is quite flexible and allows you to implement various behaviors around object access and manipulation.