0
点赞
收藏
分享

微信扫一扫

Qt扫盲-QImage 理论总结

SDKB英文 2023-10-24 阅读 43

定义:

语法:

Proxy对象由一个目标对象(target)和一个捕捉器对象(handler)组成。目标对象是被代理的对象,而捕捉器对象定义了在代理对象上执行操作时的行为。

let proxy = new Proxy(target, handler);

 Proxy 对象的所有用法,都是上面这种形式,不同的只是handler参数的写法。new Proxy()表示生成一个Proxy实例,target参数表示所要拦截的目标对象,handler参数也是一个对象,用来定制拦截行为。

使用方法:

属性访问拦截:

const target = {
  name: 'Alice',
  age: 25
};

const handler = {
  get: function(target, prop) {
    console.log(`访问属性: ${prop}`);
    return target[prop];
  }
};

const proxy = new Proxy(target, handler);
console.log(proxy.name); // 输出: "访问属性: name",然后输出 "Alice"

属性赋值拦截:

const target = {
  name: 'Alice',
  age: 25
};

const handler = {
  set: function(target, prop, value) {
    console.log(`设置属性: ${prop} 值为 ${value}`);
    target[prop] = value;
  }
};

const proxy = new Proxy(target, handler);
proxy.age = 30; // 输出: "设置属性: age 值为 30"
console.log(proxy.age); // 输出: 30

函数调用拦截:

const target = function(message) {
  console.log(`原始函数被调用,传入参数: ${message}`);
};

const handler = {
  apply: function(target, thisArg, args) {
    console.log(`函数调用拦截,参数: ${args}`);
    target.apply(thisArg, args);
  }
};

const proxy = new Proxy(target, handler);
proxy('Hello!'); // 输出: "函数调用拦截,参数: Hello!",然后输出 "原始函数被调用,传入参数: Hello!"

常见实例方法:

get():

set():

apply():

举报

相关推荐

0 条评论