JS: Proxy中的 Handler

175 阅读1分钟
  • Proxy 可以给我们的变量加上众多代理, 从而达成我们的目的, 而不需要修改obj自身

function sum(a, b) {
  return a + b;
}

const handler = {
    // 用于拦截函数的调用
  apply: function(target, thisArg, argumentsList) {
    console.log(`Calculate sum: ${argumentsList}`);
    // expected output: "Calculate sum: 1,2"

    return target(argumentsList[0], argumentsList[1]) * 10;
  }
};

const proxy1 = new Proxy(sum, handler);

console.log(sum(1, 2));
// expected output: 3
console.log(proxy1(1, 2));
// expected output: 30


其他常用的handler属性

  1. handler.apply()

  2. handler.construct()

  3. handler.defineProperty()

  4. handler.deleteProperty()

  5. handler.get()

  6. handler.getOwnPropertyDescriptor()

  7. handler.getPrototypeOf()

  8. handler.has()

  9. handler.isExtensible()

  10. handler.ownKeys()

  11. handler.preventExtensions()

  12. handler.set()

  13. handler.setPrototypeOf()