How to get the target of a JavaScript Proxy?

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

    You can if the target is an object.

    You will have to create a function in target to retrieve it, that's all.

    Example:

    class AnyClass {
       constructor() {
          this.target = this;
    
          return new Proxy(this, this);
       }
    
       get(obj, prop) {
          if (prop in obj)
              return this[prop];
    
          // your stuff here
       }
    
       getTarget() {
          return this.target;
       }
    }
    

    And then when you call:

    let sample = new AnyClass;
    console.log(sample.getTarget());
    

    Will return you the target as you expect :)

提交回复
热议问题