How to get the target of a JavaScript Proxy?

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

    There is a clever way to do this - You can add a get trap to the proxy and have it return the target conditionally. Like so..

    let resolveMode = false;  // Switch that controls if getter returns target or prop. 
    
    function resolve(obj) {
        resolveMode = true;  // Turn on our switch
        let target = obj.anything;  // This gets the target not the prop!
        resolveMode = false;  // Turn off the switch for the getter to behave normally
        return target;  // Return what we got!
    }
    
    function createProxy() {
        const myArray = [Math.random(), Math.random()];
        return new Proxy(myArray, {
            get: function(target, prop) {
                if (resolveMode) return target;  // This is where the magic happens!
                else return target[prop];        // This is normal behavior..
            }
        });
    }
    
    const myProxy = createProxy();
    let target = resolve(myProxy);
    

    Remember that the more lines of code you add to traps, the slower the object's performance gets. Hope this helps.

提交回复
热议问题