最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Retrieve original target object from existing proxy instance - Stack Overflow

programmeradmin1浏览0评论

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
 |  Show 6 more comments

3 Answers 3

Reset to default 11

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
发布评论

评论列表(0)

  1. 暂无评论