zoukankan      html  css  js  c++  java
  • [Javascript] Implementing proxy handler with Proxy

    For a Proxy, function signature looks like:

    const target = {}
    const handler = {
        get(target, propKey) {
            return Reflect.get(target, propKey)
        }
    }
    const proxy = new Proxy(target, handler)

    We implement handler with 'get' function. But there is still lots of function which can be implemented. Docs

    To make it easy, to can use another Proxy to impelemnt the handler:

    const handler = new Proxy({}, {
        get(target, trapName. receiver) {
            // Return the handler method named trapName
            return (...args) => {
                return Reflect[trapName](...args);
            };
        },
    });

    The reason that we can use 'Reflect' is because, Proxy's handler and Reflect API are the same.

    Using:

    const handler = new Proxy({}, {
      get(target, trapName, receiver) {
        // Return the handler method named trapName
        return (...args) => {
          console.log(trapName.toUpperCase() + ' ' + args[1]);
          // Forward the operation
          return Reflect[trapName](...args);
        };
      },
    });
    
    const target = {};
    const proxy = new Proxy(target, handler);
    
    proxy.distance = 450; // set
    assert.equal(proxy.distance, 450); // get
  • 相关阅读:
    SQLI DUMB SERIES-12
    SQLI DUMB SERIES-11
    SQLI DUMB SERIES-9&&10
    SQLI DUMB SERIES-8
    SQLI DUMB SERIES-7
    XXS level10
    XXS level9
    XXS level8
    XXS level7
    XXS level6
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13569151.html
Copyright © 2011-2022 走看看