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()
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()
Share
Improve this question
edited Nov 10, 2017 at 5:45
Alexander Mills
asked Nov 10, 2017 at 5:17
Alexander MillsAlexander Mills
100k165 gold badges531 silver badges908 bronze badges
11
- No, but there might be nonstandard methods. See stackoverflow.com/a/38385693/283863 – Derek 朕會功夫 Commented Nov 10, 2017 at 5:28
- Can you add that comment as an answer – Alexander Mills Commented Nov 10, 2017 at 5:29
- 1 Frankly I think this question is very similar to the one I mentioned, although that one is about getting the handler instead of the original target. I can write that as answer but I think the answer on that page is already sufficient. – Derek 朕會功夫 Commented Nov 10, 2017 at 5:33
- This is more about the exact API call if there is one for this, since there appear to be no documents for this specific call that I can find. – Alexander Mills Commented Nov 10, 2017 at 5:34
- You can’t. Also, don’t use proxies for anything, ever. – Ry- ♦ Commented Nov 10, 2017 at 5:50
3 Answers
Reset to default 11Just 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