How to get the target of a JavaScript Proxy?

后端 未结 8 1861
野趣味
野趣味 2020-12-18 19:29
function createProxy() {
    const myArray = [Math.random(), Math.random()];
    return new Proxy(myArray, {});
}

const myProxy = createProxy();

H

相关标签:
8条回答
  • 2020-12-18 20:07

    I find that (using Vue.js where sometimes Proxy objects are involved, e.g. when watching a component prop) I can obtain the target both if it is an Object and if it is an Array using JSON.stringify:

    let myTarget = JSON.parse(JSON.stringify(myProxy))
    

    This approach works also with Array targets, whereas Object.assign({}, myProxy) works only if the target is an Object.

    But I am very new to JavaScript proxies and my knowledge is limited. I may not understand the limitations and caveats of this approach. Nevertheless, maybe it helps someone!

    0 讨论(0)
  • 2020-12-18 20:10

    You can make a copy of the data returned by the proxy using Object.assign():

    const target_copy = Object.assign({}, my_proxy);
    

    This will work for all enumerable own properties existing on the proxy/target.

    0 讨论(0)
提交回复
热议问题