Proxy 无法拦截 super 调用,因为 super 在语言层面直接访问原型链上的方法,不经过对象属性查找机制,因此不会触发 get 或 apply 等 trap 捕获器;例如在类的继承中,super.greet() 直接从 Parent.prototype 查找方法,即使 Child.prototype 的原型被代理,也不会触发 Proxy 的捕获器;虽然无法直接拦截,但可通过代理父类原型间接影响 super 行为,如将 Parent.prototype 替换为 Proxy,在 get 中拦截方法调用并添加额外逻辑;这表明 super 的调用是静态解析且绕过代理机制的,只能通过修改原型链或代理父级原型实现间接控制。

JavaScript 的 Proxy 无法直接拦截 super 关键字的方法调用。
const target = {
greet() {
return "Hello from target";
}
};
const handler = {
get(target, prop, receiver) {
console.log(`Access to ${prop}`);
return Reflect.get(...arguments);
}
};
const proxy = new Proxy(target, handler);
class Parent {
greet() {
return "Hello from Parent";
}
}
class Child extends Parent {
greet() {
// 这里 super.greet() 访问的是 Parent.prototype.greet
// 即使 this.__proto__ 可能被代理,super 仍然直接找 Parent.prototype
return super.greet() + ", then Child";
}
}
// 把 Child 实例的原型换成代理
Object.setPrototypeOf(Child.prototype, proxy);
const c = new Child();
console.log(c.greet()); // 输出: "Hello from Parent, then Child"
// 注意:没有触发 Proxy 的 get 捕获器
const parentProtoProxy = new Proxy(Parent.prototype, {
get(target, prop, receiver) {
if (prop === 'greet') {
return function(...args) {
console.log('Intercepted super.greet() call');
return Reflect.get(target, prop, receiver).apply(this, args);
};
}
return Reflect.get(...arguments);
}
});
// 让 Child 继承自被代理的原型
Object.setPrototypeOf(Child.prototype, parentProtoProxy);
基本上就这些。Proxy 对 super 的调用无能为力,因为 super 是静态解析、直接访问原型的机制,不走常规的对象属性陷阱路径。想监控或修改 super 行为,只能从父级原型入手,而非靠代理子类或实例。
以上就是JavaScript 的 Proxy 能否拦截 super 关键字的方法调用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号