PHP前端开发

JavaScript 中的代理

百变鹏仔 3天前 #JavaScript
文章标签 JavaScript

javascript 中的代理是一个特殊的对象,它允许您自定义另一个对象上的基本操作(例如,属性查找、赋值、枚举、函数调用等)的行为。这就像有一个淘气的中间人可以拦截并改变与物体的交互。

为什么我们需要代理?

代理有多种用途:

  1. 验证: 通过验证分配来确保数据完整性。
    日志记录:跟踪对象上的操作以进行调试或监控。

  2. 默认值: 访问属性时提供默认值。

  3. 访问控制:限制或修改对某些属性的访问。

    立即学习“Java免费学习笔记(深入)”;

  4. 虚拟属性: 定义对象上物理上不存在的属性。

理解代理的有趣例子

例子一:过度保护的父母

想象一下您有一个名叫蒂米的孩子,您想确保他不吃太多饼干。你就像一个过度保护的父母,监视和控制他的饼干摄入量。

let timmy = {  cookies: 3};let overprotectiveParent = new Proxy(timmy, {  get(target, property) {    console.log(`Overprotective Parent: "Timmy currently has ${target[property]} ${property}."`);    return target[property];  },  set(target, property, value) {    if (property === 'cookies' && value > 5) {      console.log('Overprotective Parent: "No, Timmy, you can’t have more than 5 cookies!"');      return false;    }    console.log(`Overprotective Parent: "Alright, Timmy, you can have ${value} ${property}."`);    target[property] = value;    return true;  }});// Checking Timmy's cookiesconsole.log(overprotectiveParent.cookies); // Overprotective Parent: "Timmy currently has 3 cookies."// Trying to give Timmy too many cookiesoverprotectiveParent.cookies = 6; // Overprotective Parent: "No, Timmy, you can’t have more than 5 cookies!"// Setting a reasonable number of cookiesoverprotectiveParent.cookies = 4; // Overprotective Parent: "Alright, Timmy, you can have 4 cookies."console.log(overprotectiveParent.cookies); // Overprotective Parent: "Timmy currently has 4 cookies."