proxy 代理模式中拦截构造函数的核心是 construct 拦截器,专用于 new 操作,可校验参数、预处理或返回自定义实例,但必须返回对象且仅支持可构造函数。

Proxy 代理模式中拦截构造函数的实例化,核心是使用 construct 拦截器。它专为 new 操作设计,能在真正创建实例前介入参数处理、校验或替换返回值。
construct 拦截器的基本用法
当对 Proxy 实例执行 new 操作时,construct(target, args, newTarget) 会被触发:
- target:原始构造函数(即被代理的目标)
-
args:传给
new的参数列表(数组形式) -
newTarget:实际被
new调用的构造器(通常是 Proxy 本身,可用于区分直接调用与继承场景)
必须返回一个对象,否则会抛出 TypeError;不能返回原始值(如字符串、数字)。
参数校验与预处理
可在 construct 中对 args 做清洗、默认填充或合法性检查:
FastAPI + Flask 混合部署最佳实践,解决路由定义、API 代理等常见问题,适用于同时运行 FastAPI API 与 Flask 前端的场景。
- 拒绝非法参数(如类型错误、空值),提前抛错,阻止实例创建
- 自动转换参数类型(如将字符串 age 转为数字)
- 补充缺失参数(例如未传 name 时设为 'anonymous')
示例:
const User = class { constructor(name, age) { this.name = name; this.age = age; } };const proxiedUser = new Proxy(User, {
construct(target, args) {
if (!args[0] || typeof args[0] !== 'string') throw new Error('name required');
const safeArgs = [args[0], Math.max(0, Math.min(150, args[1] ?? 0))];
return new target(...safeArgs);
}
});
new proxiedUser('Bob', 30); // ✅ 正常
new proxiedUser(null, 200); // ❌ 抛错,构造函数未执行
返回自定义实例(非 target 构造结果)
construct 允许返回任意对象,不一定要调用 new target(...):
- 可返回缓存实例(实现简单单例或对象池)
- 可返回包装后的代理对象(如添加日志、响应式逻辑)
- 可返回子类实例(动态选择派生类)
注意:若返回对象不是 newTarget 的实例,instanceof 检查可能失败,需配合 getPrototypeOf 或手动设置原型。
兼容性与限制
construct 在现代浏览器和 Node.js(v6+)中广泛支持,但需留意:
- 不能代理箭头函数或普通函数(仅适用于可被
new调用的函数,包括 class) - 某些严格环境(如旧版 Safari)可能对类代理有限制
- 若目标构造函数内部依赖
this.constructor或new.target,返回自定义对象时需谨慎处理原型链










