Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve original target object from existing proxy instance

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()
like image 634
Alexander Mills Avatar asked Nov 10 '17 05:11

Alexander Mills


3 Answers

Just destructure it into a new object:

myNewSimpleObject = {...myProxy}

Cheers!

like image 104
Adrian Nuske Avatar answered Sep 19 '22 09:09

Adrian Nuske


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
like image 43
Terbiy Avatar answered Sep 23 '22 09:09

Terbiy


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
like image 22
Luke Scales Avatar answered Sep 20 '22 09:09

Luke Scales