You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Proxy代理Array.prototype.push实现调用时触发自定义逻辑?

实现Array.prototype.push的代理拦截

要实现你想要的效果,核心是把Array.prototype.push替换为它的代理版本,这样所有数组实例调用push时都会触发代理的拦截逻辑。具体实现如下:

代码示例

// 定义代理处理器,拦截函数调用
const pushProxyHandler = {
  apply(target, thisArg, args) {
    // 先执行原生push方法,保证数组功能正常
    const result = Reflect.apply(target, thisArg, args);
    // 打印传入的元素(对应你需求里的打印"e")
    console.log(args[0]);
    // 返回原生push的结果(数组新长度)
    return result;
  }
};

// 替换Array.prototype.push为代理后的函数
Array.prototype.push = new Proxy(Array.prototype.push, pushProxyHandler);

// 测试
const array = [];
array.push("e"); // 控制台打印"e",同时数组变为["e"]

关键说明

  • 直接执行new Proxy(Array.prototype.push, handler)不会生效,因为这只是创建了一个代理对象,但没有覆盖原生的push方法。必须把代理后的函数赋值回Array.prototype.push,才能让所有数组实例继承这个代理方法。
  • 代理的apply陷阱会在函数被调用时触发:
    • target是原生的push方法
    • thisArg是调用push的数组实例(也就是示例中的array)
    • args是调用push时传入的参数列表(示例中是["e"])
  • 使用Reflect.apply可以确保原生push方法的行为完全保留,避免破坏原有功能。

内容的提问来源于stack exchange,提问作者bread

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:04:56