How to get the target of a JavaScript Proxy?

后端 未结 8 1885
野趣味
野趣味 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:00

    How about adding the following get trap:

    const handler = {
      get: (target, property, receiver) => {
        if (property === 'myTarget') {
          return target
        }
        return target[property]
      }
    }
    
    const myArray = [Math.random(), Math.random()];
    
    function createProxy() {
    //     const myArray = [Math.random(), Math.random()];
        return new Proxy(myArray, handler);
    }
    
    const myProxy = createProxy();
    

    And you can get the target of the proxy by myProxy.myTarget:

    console.log(myProxy.myTarget) // [0.22089416118932403, 0.08429264462405173]
    console.log(myArray === myProxy.myTarget) // true
    

提交回复
热议问题