JavaScript中的Proxy详解

1. 什么是Proxy?

Proxy是ES6引入的一个强大特性,它允许你创建一个对象的代理,从而可以拦截和自定义该对象的基本操作。Proxy提供了一种机制,可以在对象的基本操作,如属性查找、赋值、枚举、函数调用等之前或之后执行自定义行为。

基本语法如下:

const proxy = new Proxy(target, handler);

target:要代理的目标对象,可以是任何类型的对象,包括数组、函数或另一个代理;

handler:一个对象,其属性是定义代理行为的函数,称为"陷阱"或"trap";

2. 所有的handler方法

2.1. get(target, prop, receiver) - 拦截属性读取

const person = {name: "Alice",age: 30,
};const proxy = new Proxy(person, {get(target, prop) {console.log(`Reading property: ${prop}`);return prop in target ? target[prop] : "Default";},
});console.log(proxy.name); // "Reading property: name" → "Alice"
console.log(proxy.gender); // "Reading property: gender" → "Default"

2.2. set(target, prop, value, receiver) - 拦截属性设置

const validator = {set(target, prop, value) {if (prop === "age") {if (!Number.isInteger(value) || value < 0) {throw new TypeError("Age must be a positive integer");}}console.log(`Setting ${prop} to ${value}`);target[prop] = value;return true; // 表示设置成功},
};const person = new Proxy({}, validator);
person.age = 25; // "Setting age to 25"
person.age = -5; // 抛出错误: Age must be a positive integer

2.3. has(target, prop) - 拦截 in 操作符

const hiddenProps = ["secret", "password"];
const target = {name: "Bob",secret: "123",
};const proxy = new Proxy(target, {has(target, prop) {if (hiddenProps.includes(prop)) {return false; // 隐藏属性}return prop in target;},
});console.log("name" in proxy); // true
console.log("secret" in proxy); // false

2.4. deleteProperty(target, prop) - 拦截 delete 操作

const protectedData = {name: "Charlie",id: "12345",
};const proxy = new Proxy(protectedData, {deleteProperty(target, prop) {if (prop === "id") {throw new Error("Cannot delete ID property");}delete target[prop];return true;},
});delete proxy.name; // 成功
delete proxy.id; // 抛出错误: Cannot delete ID property

2.5. apply(target, thisArg, arguments) - 拦截函数调用

function sum(a, b) {return a + b;
}const loggingProxy = new Proxy(sum, {apply(target, thisArg, args) {console.log(`Function called with args: ${args}`);console.log(`thisArg: ${thisArg}`);const result = target.apply(thisArg, args);console.log(`Function returned: ${result}`);return result;},
});loggingProxy(2, 3);
// "Function called with args: 2,3"
// "thisArg: undefined"
// "Function returned: 5"
// → 5

2.6. construct(target, argumentsList, newTarget) - 拦截 new 操作符

class Person {constructor(name) {this.name = name;}
}const PersonProxy = new Proxy(Person, {construct(target, args, newTarget) {console.log(`Creating instance with args: ${args}`);// 可以修改参数或添加额外逻辑if (args.length === 0) {args = ["Anonymous"];}return new target(...args);},
});const p1 = new PersonProxy("Alice");
// "Creating instance with args: Alice"
const p2 = new PersonProxy();
// "Creating instance with args:" → name: "Anonymous"

2.7. ownKeys(target) - 拦截 Object.keys() 等操作

const user = {name: "Dave",age: 40,_password: "****",
};const proxy = new Proxy(user, {ownKeys(target) {return Object.keys(target).filter((key) => !key.startsWith("_"));},
});console.log(Object.keys(proxy)); // ["name", "age"]
console.log(Object.getOwnPropertyNames(proxy)); // ["name", "age"]

2.8. getOwnPropertyDescriptor(target, prop) - 拦截 Object.getOwnPropertyDescriptor()

const target = {name: "Eve",
};const proxy = new Proxy(target, {getOwnPropertyDescriptor(target, prop) {console.log(`Getting descriptor for: ${prop}`);const descriptor = Object.getOwnPropertyDescriptor(target, prop);// 可以修改描述符if (prop === "name") {descriptor.enumerable = false;}return descriptor || undefined;},
});console.log(Object.getOwnPropertyDescriptor(proxy, "name"));
// "Getting descriptor for: name" → {value: "Eve", writable: true, enumerable: false, configurable: true}

2.9. defineProperty(target, prop, descriptor) - 拦截 Object.defineProperty()

const target = {};const proxy = new Proxy(target, {defineProperty(target, prop, descriptor) {console.log(`Defining property ${prop}`);if (prop.startsWith("_")) {throw new Error(`Cannot define private property: ${prop}`);}return Reflect.defineProperty(target, prop, descriptor);},
});Object.defineProperty(proxy, "name", { value: "Frank" }); // 成功
Object.defineProperty(proxy, "_secret", { value: "123" }); // 抛出错误

2.10. preventExtensions(target) - 拦截 Object.preventExtensions()

const target = { name: "Grace" };
const proxy = new Proxy(target, {preventExtensions(target) {console.log("Attempt to prevent extensions");// 可以决定是否允许阻止扩展return false; // 返回false表示不允许阻止扩展// 或者调用 Reflect.preventExtensions(target)},
});Object.preventExtensions(proxy);
// "Attempt to prevent extensions"
// 抛出 TypeError (因为返回了false)

2.11. isExtensible(target) - 拦截 Object.isExtensible()

const target = {};const proxy = new Proxy(target, {isExtensible(target) {console.log("Checking extensibility");// 可以返回自定义值return false; // 总是返回不可扩展// 或者调用 Reflect.isExtensible(target)},
});console.log(Object.isExtensible(proxy));
// "Checking extensibility" → false

2.12. getPrototypeOf(target) - 拦截 Object.getPrototypeOf()

const originalProto = { version: 1 };
const obj = Object.create(originalProto);const proxy = new Proxy(obj, {getPrototypeOf(target) {console.log("Getting prototype");// 可以返回不同的原型return { version: 2 }; // 返回假原型// 或者调用 Reflect.getPrototypeOf(target)},
});console.log(Object.getPrototypeOf(proxy));
// "Getting prototype" → {version: 2}

2.13. setPrototypeOf(target, prototype) - 拦截 Object.setPrototypeOf()

const target = {};
const proxy = new Proxy(target, {setPrototypeOf(target, proto) {console.log(`Setting prototype to: ${proto}`);// 可以阻止设置原型throw new Error("Prototype modification not allowed");// 或者调用 Reflect.setPrototypeOf(target, proto)},
});Object.setPrototypeOf(proxy, {});
// "Setting prototype to: [object Object]"
// 抛出错误: Prototype modification not allowed

2.14. 综合示例:实现一个全面的数据验证代理

const createValidatedObject = (schema, initialData = {}) => {return new Proxy(initialData, {set(target, prop, value) {// 检查属性是否在schema中定义if (!(prop in schema)) {throw new Error(`Property "${prop}" is not allowed`);}// 获取验证函数const validator = schema[prop];// 验证值if (!validator(value)) {throw new Error(`Invalid value for property "${prop}"`);}// 设置值target[prop] = value;return true;},get(target, prop) {if (prop in target) {return target[prop];}throw new Error(`Property "${prop}" does not exist`);},deleteProperty(target, prop) {if (prop in schema && !schema[prop].configurable) {throw new Error(`Cannot delete property "${prop}"`);}delete target[prop];return true;},});
};// 定义schema
const userSchema = {name: (value) => typeof value === "string" && value.length > 0,age: (value) => Number.isInteger(value) && value >= 0,email: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
};// 创建代理对象
const user = createValidatedObject(userSchema);// 使用示例
user.name = "Alice"; // 成功
user.age = 30; // 成功
user.email = "alice@example.com"; // 成功try {user.age = -5; // 抛出错误: Invalid value for property "age"
} catch (e) {console.error(e.message);
}try {user.gender = "female"; // 抛出错误: Property "gender" is not allowed
} catch (e) {console.error(e.message);
}

这些示例涵盖了 Proxy 的主要 handler 方法,展示了它们在实际开发中的应用场景。通过这些示例,你可以看到 Proxy 如何为 JavaScript 对象提供强大的拦截和自定义能力。

3. 常用场景

下面是Proxy在实际开发中的10种常见应用场景的完整代码示例:

3.1. 数据验证

const createValidator = (rules) => {return new Proxy({},{set(target, prop, value) {if (!rules[prop]) {throw new Error(`Property "${prop}" is not allowed`);}if (!rules[prop](value)) {throw new Error(`Invalid value for "${prop}"`);}target[prop] = value;return true;},});
};// 使用示例
const userValidator = createValidator({name: (val) => typeof val === "string" && val.length >= 2,age: (val) => Number.isInteger(val) && val >= 18,email: (val) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val),
});userValidator.name = "Alice"; // 成功
userValidator.age = 25; // 成功
// userValidator.age = '25'; // 抛出错误
// userValidator.gender = 'female'; // 抛出错误

3.2. 观察者模式(数据变化监听)

function createObservable(target, callback) {return new Proxy(target, {set(target, prop, value) {const oldValue = target[prop];target[prop] = value;callback(prop, oldValue, value);return true;},});
}// 使用示例
const user = { name: "Bob", age: 30 };
const observableUser = createObservable(user, (prop, oldVal, newVal) => {console.log(`Property ${prop} changed from ${oldVal} to ${newVal}`);
});observableUser.name = "Alice"; // 控制台输出: Property name changed from Bob to Alice
observableUser.age = 31; // 控制台输出: Property age changed from 30 to 31

3.3. 属性访问控制

const createPrivateProps = (obj, privateProps = []) => {return new Proxy(obj, {get(target, prop) {if (privateProps.includes(prop)) {throw new Error(`Property "${prop}" is private`);}return target[prop];},set(target, prop, value) {if (privateProps.includes(prop)) {throw new Error(`Cannot set private property "${prop}"`);}target[prop] = value;return true;},});
};// 使用示例
const account = createPrivateProps({username: "alice123",_password: "secret123",},["_password"]
);console.log(account.username); // 'alice123'
// console.log(account._password); // 抛出错误
// account._password = 'newpass'; // 抛出错误

3.4. 虚拟属性(动态计算属性)

const createVirtualProps = (obj, virtualProps = {}) => {return new Proxy(obj, {get(target, prop) {if (prop in virtualProps) {return virtualProps[prop](target);}return target[prop];},});
};// 使用示例
const person = createVirtualProps({firstName: "John",lastName: "Doe",},{fullName: (target) => `${target.firstName} ${target.lastName}`,initials: (target) => `${target.firstName[0]}${target.lastName[0]}`,}
);console.log(person.fullName); // 'John Doe'
console.log(person.initials); // 'JD'

3.5. API封装(简化复杂API)

const api = {_baseUrl: "https://api.example.com",_endpoints: {users: "/users",posts: "/posts",},_makeRequest(url, options) {console.log(`Making request to ${url}`);// 实际这里会是fetch或axios调用return Promise.resolve({ data: `${url} response` });},
};const apiProxy = new Proxy(api, {get(target, prop) {if (prop in target._endpoints) {return (options = {}) => {const url = `${target._baseUrl}${target._endpoints[prop]}`;return target._makeRequest(url, options);};}return target[prop];},
});// 使用示例
apiProxy.users().then((res) => console.log(res.data));
// "Making request to https://api.example.com/users"
// → "https://api.example.com/users response"apiProxy.posts({ page: 2 }).then((res) => console.log(res.data));
// "Making request to https://api.example.com/posts"
// → "https://api.example.com/posts response"

3.6. 性能优化(延迟加载/缓存)

const createCachedProxy = (fn) => {const cache = new Map();return new Proxy(fn, {apply(target, thisArg, args) {const key = JSON.stringify(args);if (cache.has(key)) {console.log("Returning cached result");return cache.get(key);}console.log("Calculating new result");const result = target.apply(thisArg, args);cache.set(key, result);return result;},});
};// 使用示例
const expensiveCalculation = (a, b) => {console.log("Running expensive calculation...");return a * b;
};const cachedCalc = createCachedProxy(expensiveCalculation);console.log(cachedCalc(2, 3)); // "Running expensive calculation..." → 6
console.log(cachedCalc(2, 3)); // "Returning cached result" → 6
console.log(cachedCalc(4, 5)); // "Running expensive calculation..." → 20

3.7. 负索引数组(类似Python)

const createNegativeIndexArray = (arr) => {return new Proxy(arr, {get(target, prop) {const index = parseInt(prop);if (!isNaN(index)) {// 处理负索引prop = index < 0 ? target.length + index : index;}return Reflect.get(target, prop);},});
};// 使用示例
const array = createNegativeIndexArray(["a", "b", "c", "d"]);console.log(array[0]); // 'a'
console.log(array[-1]); // 'd'
console.log(array[-2]); // 'c'

3.8. 函数调用日志(调试)

const withLogging = (fn) => {return new Proxy(fn, {apply(target, thisArg, args) {console.log(`Calling ${target.name} with args:`, args);const start = performance.now();const result = target.apply(thisArg, args);const end = performance.now();console.log(`Called ${target.name}, took ${(end - start).toFixed(2)}ms`);return result;},});
};// 使用示例
function calculate(a, b, c) {// 模拟耗时操作for (let i = 0; i < 100000000; i++) {}return a + b * c;
}const loggedCalc = withLogging(calculate);
console.log(loggedCalc(2, 3, 4));
// 控制台输出:
// Calling calculate with args: [2, 3, 4]
// Called calculate, took 123.45ms
// → 14

3.9. 自动填充默认值

const withDefaults = (obj, defaults) => {return new Proxy(obj, {get(target, prop) {if (prop in target) {return target[prop];}if (prop in defaults) {const defaultValue = defaults[prop];// 如果默认值是函数则调用它return typeof defaultValue === "function"? defaultValue(): defaultValue;}return undefined;},});
};// 使用示例
const config = withDefaults({theme: "dark",},{theme: "light",fontSize: 14,timestamp: () => new Date().toISOString(),}
);console.log(config.theme); // 'dark' (使用已有值)
console.log(config.fontSize); // 14 (使用默认值)
console.log(config.timestamp); // 当前时间ISO字符串 (调用函数默认值)
console.log(config.nonExisting); // undefined

3.10. 数据绑定(双向绑定)

function createBinding(sourceObj, targetObj, propertyMap) {const handler = {set(target, prop, value) {target[prop] = value;// 更新绑定的属性if (propertyMap[prop]) {const targetProp = propertyMap[prop];targetObj[targetProp] = value;console.log(`Updated ${targetProp} to ${value}`);}return true;},};return new Proxy(sourceObj, handler);
}// 使用示例
const form = {};
const model = { firstName: "", lastName: "" };const boundForm = createBinding(form, model, {"first-name": "firstName","last-name": "lastName",
});boundForm["first-name"] = "Alice";
// 控制台输出: Updated firstName to Alice
boundForm["last-name"] = "Smith";
// 控制台输出: Updated lastName to Smithconsole.log(model);
// { firstName: 'Alice', lastName: 'Smith' }

这些示例展示了Proxy在实际开发中的强大能力。每个示例都可以根据具体需求进行扩展和组合使用,Proxy为JavaScript提供了元编程的强大工具,可以优雅地解决许多复杂问题。

4. 注意事项

1. Proxy的handler方法中应该尽量使用Reflect对象的方法来保持默认行为;

2. 不是所有操作都可以被拦截,例如严格相等===;

3. 过度使用Proxy可能会影响性能;

4. 某些库可能无法正确处理Proxy对象;

5. Proxy的this绑定可能与原对象不同;

Proxy为JavaScript提供了强大的元编程能力,合理使用可以大大简化代码并实现复杂的功能,但也要注意不要过度使用,以免影响代码的可读性和性能。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/76931.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【git】VScode修改撤回文件总是出现.lh文件,在 ​所有 Git 项目 中全局忽略特定文件

VScode里面powershell被迫关闭 场景解决办法 场景 系统&#xff1a;Windows IDE&#xff1a;Visual Studio Code 一旦修改代码&#xff0c;就算撤回也会显示 解决办法 第一步&#xff1a;“C:\Users\用户名字.gitignore_global”&#xff1a;在该路径下新建.gitignore_glo…

为什么 LoRA 梯度是建立在全量参数 W 的梯度之上

&#x1f9e0; 首先搞清楚 LoRA 是怎么做微调的 我们原来要训练的参数矩阵是 W W W&#xff0c;但 LoRA 说&#xff1a; 别动 W&#xff0c;我在它旁边加一个低秩矩阵 Δ W U V \Delta W UV ΔWUV&#xff0c;只训练这个部分&#xff01; 也就是说&#xff0c;LoRA 用一个…

Nginx负载均衡时如何为指定ip配置固定服务器

大家在用Nginx做负载均衡时&#xff0c;一般是采用默认的weight权重指定或默认的平均分配实现后端服务器的路由&#xff0c;还有一种做法是通过ip_hash来自动计算进行后端服务器的路由&#xff0c;但最近遇到一个问题&#xff0c;就是希望大部分用户采用ip_hash自动分配后端服务…

Llama 4 家族:原生多模态 AI 创新的新时代开启

0 要点总结 Meta发布 Llama 4 系列的首批模型&#xff0c;帮用户打造更个性化多模态体验Llama 4 Scout 是有 170 亿激活参数、16 个专家模块的模型&#xff0c;同类中全球最强多模态模型&#xff0c;性能超越以往所有 Llama 系列模型&#xff0c;能在一张 NVIDIA H100 GPU 上运…

【硬件开发技巧】如何通过元器件丝印反查型号

目录 一、在线数据库查询 二、官方资料匹配 三、专业软件辅助 四、实物比对与场景推断 五、社区与人工支持 注意事项 一、在线数据库查询 专业元器件平台 Digi-Key、Mouser、ICMaster等平台支持直接输入丝印代码检索&#xff0c;可获取芯片型号、技术文档及替代型号。例如…

【算法/c++】利用中序遍历和后序遍历建二叉树

目录 题目&#xff1a;树的遍历前言题目来源树的数组存储基本思想存储规则示例 建树算法关键思路代码总代码 链表法 题目&#xff1a;树的遍历 前言 如果不是完全二叉树&#xff0c;使用数组模拟树&#xff0c;会很浪费空间。 题目来源 本题来自 PTA 天梯赛。 题目链接: 树…

李臻20242817_安全文件传输系统项目报告_第6周

安全文件传输系统项目报告&#xff08;第 1 周&#xff09; 1. 代码链接 Gitee 仓库地址&#xff1a;https://gitee.com/li-zhen1215/homework/tree/master/Secure-file 代码结构说明&#xff1a; project-root/├── src/ # 源代码目录│ ├── main.c # 主程序入口│ ├…

嵌入式rodata段

在嵌入式软件开发中&#xff0c;将数据放入只读数据段&#xff08;.rodata&#xff09;具有以下好处及典型应用示例&#xff1a; 好处 数据保护 .rodata段的内容在程序运行时不可修改&#xff0c;防止意外或恶意篡改&#xff0c;提升系统稳定性。 节省RAM资源 只读数据可直接…

InfoSec Prep: OSCP靶场渗透

InfoSec Prep: OSCP InfoSec Prep: OSCP ~ VulnHubInfoSec Prep: OSCP, made by FalconSpy. Download & walkthrough links are available.https://www.vulnhub.com/entry/infosec-prep-oscp,508/ 1&#xff0c;将两台虚拟机网络连接都改为NAT模式 2&#xff0c;攻击机上做…

【JavaWeb-Spring boot】学习笔记

目录 <<回到导览Spring boot1. http协议1.1.请求协议1.2.响应协议 2.Tomcat2.1.请求2.1.1.apifox2.1.2.简单参数2.1.3.实体参数2.1.4.数组集合参数2.1.5.日期参数2.1.6.(重点)JSON参数2.1.7.路径参数 2.2.响应2.3.综合练习 3.三层架构3.1.三层拆分3.2.分层解耦3.3.补充 &…

C++的多态-上

目录 多态的概念 多态的定义及实现 1.虚函数 2. 多态的实现 2.1.多态构成条件 2.2.虚函数重写的两个例外 (1)协变(基类与派生类虚函数返回值类型不同) (2)析构函数的重写(基类与派生类析构函数的名字不同) 2.3.多态的实现 2.4.多态在析构函数中的应用 2.5.多态构成条…

网络安全的重要性与防护措施

随着信息技术的飞速发展&#xff0c;互联网已经成为我们日常生活、工作和学习的必需品。无论是通过社交媒体与朋友互动&#xff0c;还是在网上进行银行交易&#xff0c;网络已经渗透到我们生活的方方面面。然而&#xff0c;随之而来的是各种网络安全问题&#xff0c;包括数据泄…

CMake学习--Window下VSCode 中 CMake C++ 代码调试操作方法

目录 一、背景知识二、使用方法&#xff08;一&#xff09;安装扩展&#xff08;二&#xff09;创建 CMake 项目&#xff08;三&#xff09;编写代码&#xff08;四&#xff09;配置 CMakeLists.txt&#xff08;五&#xff09;生成构建文件&#xff08;六&#xff09;开始调试 …

访问数组元素(四十四)

1. 数组下标与类型 数组的索引从 0 开始。例如&#xff0c;一个包含 10 个元素的数组&#xff0c;其合法下标范围为 0 到 9&#xff0c;而不是 1 到 10。为了表示下标&#xff0c;通常使用 size_t 类型&#xff0c;它是一种与机器相关的无符号整型&#xff0c;足够大以存放内存…

计算机网络 3-1 数据链路层(功能+组帧+差错控制)

【考纲内容】 &#xff08;一&#xff09;数据链路层的功能 &#xff08;二&#xff09;组帧 &#xff08;三&#xff09;差错控制 检错编码&#xff1b;纠错编码 &#xff08;四&#xff09;流量控制与可靠传输机制 流量控制、可靠传输与滑动窗口机制&#xff1b;停止-等…

Django中使用不同种类缓存的完整案例

Django中使用不同种类缓存的完整案例 推荐超级课程: 本地离线DeepSeek AI方案部署实战教程【完全版】Docker快速入门到精通Kubernetes入门到大师通关课AWS云服务快速入门实战目录 Django中使用不同种类缓存的完整案例步骤1:设置Django项目步骤2:设置URL路由步骤3:视图级别…

Spring Boot 集成Redis 的Lua脚本详解

1. 对比Lua脚本方案与Redis自身事务 对比表格 对比维度Redis事务&#xff08;MULTI/EXEC&#xff09;Lua脚本方案原子性事务命令序列化执行&#xff0c;但中间可被其他命令打断&#xff0c;不保证原子性Lua脚本在Redis单线程中原子执行&#xff0c;不可中断计算能力仅支持Red…

【大模型】DeepSeek + 蓝耕MaaS平台 + 海螺AI生成高质量视频操作详解

目录 一、前言 二、蓝耘智能云MaaS平台介绍 2.1 蓝耘智算平台是什么 2.2 平台优势 2.3 平台核心能力 三、海螺AI视频介绍 3.1 海螺AI视频是什么 3.2 海螺AI视频主要功能 3.3 海螺AI视频应用场景 3.4 海螺AI视频核心优势 3.5 项目git地址 四、蓝耘MaaS平台DeepSeek海…

12-产品经理-维护模块

需求模块是帮助产品经理进行需求的分类和维护。 1. 维护模块 在具体产品的“研发需求”页面左侧&#xff0c;点击“维护模块”。也可以在具体产品的“设置”-“模块”下进行维护。 点击保存后&#xff0c;返回模块页面。还可以点击“子模块”对已有模块进行子模块的维护。 点击…

考研单词笔记 2025.04.06

area n领域&#xff0c;范围&#xff0c;方面&#xff0c;地区&#xff0c;地方&#xff0c;场地&#xff0c;面积 aspect n方面&#xff0c;层面&#xff0c;外表&#xff0c;外观 boundary n限度&#xff0c;界限&#xff0c;分界线&#xff0c;边界 cap n最高限额&#x…