How to get the target of a JavaScript Proxy?

后端 未结 8 1882
野趣味
野趣味 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 19:43

    Like the other answers already said a proxy get trap can be an elegant solution.

    const IDENTITY = Symbol('proxy_target_identity')
    const handler = {
      get: (target, property, receiver) => {
        if (property === IDENTITY && !target.hasOwnProperty(IDENTITY)) { // missing '!'
          return target
        }
        return Reflect.get(target, property, receiver)
      }
    }
    function createProxy() {
        const myArray = [Math.random(), Math.random()];
        return new Proxy(myArray, handler);
    }
    const myProxy = createProxy();
    const orignal_target = myProxy[IDENTITY]
    

    This code sample should be quite robust as it:

    • avoids property name conflicts by using a Symbol
    • covers all get-scenarios by using Reflect.get instead of target[property]
    • works with prototype-inheritance - in case your proxy ends up being used as a prototype your inheritee will not return itself despite never being actually proxied itself.

提交回复
热议问题