Say I have a proxy instance like so:
const getProxy = function(){
return new Proxy({}, ...);
}
const proxy = getProxy();
later on, I want to retrieve the target from the proxy, is there some way to do this? something like:
const target = proxy.getOriginalTarget()
Just destructure it into a new object:
myNewSimpleObject = {...myProxy}
Cheers!
I haven't heard of standard solution, but you can build your factory function which returns new Proxy
object with custom property:
function buildProxy(target, handler) {
const proxy = new Proxy(target, handler);
proxy.originalTarget = target;
return proxy;
}
const test = {};
const handler = {};
buildProxy(test, handler).originalTarget === test; // true
One hack I've used to get around this in some circumstances is to use JSON.stringify to strip the Proxy object and then JSON.parse to return it as an object:
const test = {name: 'Proxy', test: true};
const handler = {};
const proxy = new Proxy(test, handler); // Proxy {name: "Proxy", test: true}
originalTarget = JSON.parse(JSON.stringify(proxy)); // {name: 'Proxy', test: true}
One important thing to note with this hack is that the properties of the new object can be equated to the properties of the original, but the whole object cannot, e.g:
originalTarget === test // false
originalTarget == test // false
originalTarget.name === test.name // true
originalTarget.test === test.test // true
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