I would like to test if a JavaScript object is a Proxy. The trivial approach
if (obj instanceof Proxy) ...
doesn't work here, nor does traversing the prototype chain for Proxy.prototype
, since all relevant operations are effectively backed by the underlying target.
Is it possible to test if an arbitrary object is a Proxy?
A proxy object acts as an intermediary between the client and an accessible object. The purpose of the proxy object is to monitor the life span of the accessible object and to forward calls to the accessible object only if it is not destroyed.
In JavaScript, proxies (proxy object) are used to wrap an object and redefine various operations into the object such as reading, insertion, validation, etc. Proxy allows you to add custom behavior to an object or a function.
The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
ES6 proxies sit between your code and an object. A proxy allows you to perform meta-programming operations such as intercepting a call to inspect or change an object's property. The following terminology is used in relation to ES6 proxies: target. The original object the proxy will virtualize.
In my current project I also needed a way of defining if something was already a Proxy, mainly because I didn't want to start a proxy on a proxy. For this I simply added a getter to my handler, which would return true if the requested variable was "__Proxy":
function _observe(obj) { if (obj.__isProxy === undefined) { var ret = new Proxy(obj || {}, { set: (target, key, value) => { /// act on the change return true; }, get: (target, key) => { if (key !== "__isProxy") { return target[key]; } return true; } }); return ret; } return obj; }
Might not be the best solution, but I think it's an elegant solution, which also doesn't pop up when serializing.
In Node.js 10 you can use util.types.isProxy
.
For example:
const target = {};
const proxy = new Proxy(target, {});
util.types.isProxy(target); // Returns false
util.types.isProxy(proxy); // Returns true
Create a new symbol:
let isProxy = Symbol("isProxy")
Inside the get
method of your proxy handler you can check if the key
is your symbol and then return true
:
get(target, key)
{
if (key === isProxy)
return true;
// normal get handler code here
}
You can then check if an object is one of your proxies by using the following code:
if (myObject[isProxy]) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With