实例对象的函数批量劫持

25 阅读1分钟

把html部分粘贴出去可以直接测试了。

对函数做统一的拦截,统一对所有实例对象的方法做统一处理的场合使用该方法。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>实例对象的函数批量劫持</h1>
  <script>
    class Per{
      sayHi=(str)=>{
        console.log('sayHi-------------99999', str);
      }
      fly=(data)=>{
        console.log('fly-------------99999', data);
      }
      hehe=(a,b)=>{
        console.log('hehe-------------99999',a,b);
      }
      haha=(a,b,c)=>{
        console.log('haha-------------99999',a,b,c);
      }
    }
    class Person extends Per{
      constructor(name, age){
        super(name, age);
        this.name = name;
        this.age = age;
      }
    }

    // InstanceObject 实例对象:要求是 new 出来的。
    // 对函数做统一的拦截,添加统一日志使用
    const hijackingFunc = (InstanceObject)=>{
      return new Proxy(InstanceObject, {
        get(target, prop, receiver) {
          const origMethod = target[prop];
          if (typeof origMethod === "function") {
            return function (...args) {
              // prop  就是函数名, 
              console.log(`Method '${prop}' called with args: `,JSON.stringify(args) );
              const result = origMethod.apply(this, args);
              return result;
            };
          } else {
            return origMethod;
          }
        },
      });
    }

    const proxy = hijackingFunc(new Person("Tom", 18))
  
    proxy.sayHi('sssss');
    proxy.fly({a:1,b:2});
    proxy.hehe('a', 'b');
    proxy.haha('a','s', 'w');
  </script>
</body>
</html>

js部分

class Per{
      sayHi=(str)=>{
        console.log('sayHi-------------99999', str);
      }
      fly=(data)=>{
        console.log('fly-------------99999', data);
      }
      hehe=(a,b)=>{
        console.log('hehe-------------99999',a,b);
      }
      haha=(a,b,c)=>{
        console.log('haha-------------99999',a,b,c);
      }
    }
    class Person extends Per{
      constructor(name, age){
        super(name, age);
        this.name = name;
        this.age = age;
      }
      
    }

    // InstanceObject 实例对象:要求是 new 出来的。
    // 对函数做统一的拦截,添加统一日志使用
    const hijackingFunc = (InstanceObject)=>{
      return new Proxy(InstanceObject, {
        get(target, prop, receiver) {
          const origMethod = target[prop];
          if (typeof origMethod === "function") {
            return function (...args) {
              // prop  就是函数名, 
              console.log(`Method '${prop}' called with args: `,JSON.stringify(args) );
              const result = origMethod.apply(this, args);
              return result;
            };
          } else {
            return origMethod;
          }
        },
      });
    }

    const proxy = hijackingFunc(new Person("Tom", 18))
  
    proxy.sayHi('sssss');
    proxy.fly({a:1,b:2});
    proxy.hehe('a', 'b');
    proxy.haha('a','s', 'w');