How to get the target of a JavaScript Proxy?

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

    The other answers gave some good solutions. Here is @Yuci's answer distilled down for classes, in which case, it's as simple as defining an instance variable of some special name. The Proxy get function returns it, and so does the underlying target.

    class Foo {
        constructor() {
            this.__target__ = this;
            return new Proxy(this, {
                get: function (target, name) {
                    if (name in target) return target[name];
                    // your code here
                }
            });
        }
    }
    
    let foo = new Foo();
    let target = foo.__target__;
    console.log('proxied Foo', foo);
    console.log('recovered target', target, target.__target__.__target__);
    

提交回复
热议问题