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

如何使用JavaScript Proxy为嵌套对象的所有函数调用结果加1?

给对象中所有函数返回值加1的Proxy实现方案

因为目标对象本身不是函数,没法直接在对象的Proxy上使用apply陷阱。我们可以通过拦截对象的属性访问,对每个函数单独包装一层Proxy来实现需求:

基础实现(平级对象)

const testObj = {
  add: (a: number, b: number) => a + b,
  subtract: (a: number, b: number) => a - b,
  multiply: (a: number, b: number) => a * b,
};

const proxy = new Proxy(testObj, {
  get(target, prop) {
    const value = target[prop as keyof typeof target];
    // 仅对函数类型的属性进行包装
    if (typeof value === 'function') {
      return new Proxy(value, {
        apply(_target, thisArg, args) {
          // 执行原函数获取结果
          const result = _target.apply(thisArg, args);
          // 给结果加1后返回
          return result + 1;
        },
      });
    }
    // 非函数属性直接返回原值
    return value;
  },
});

// 测试验证
console.log(proxy.add(1, 2)); // 输出 4(1+2+1)
console.log(proxy.subtract(5, 3)); // 输出 3(5-3+1)
console.log(proxy.multiply(2, 3)); // 输出 7(2*3+1)

扩展支持嵌套对象

如果你的对象存在嵌套结构,可以通过递归创建Proxy来覆盖所有层级的函数:

const createResultAddOneProxy = (obj: any) => {
  return new Proxy(obj, {
    get(target, prop) {
      const value = target[prop];
      if (typeof value === 'function') {
        return new Proxy(value, {
          apply(_target, thisArg, args) {
            const result = _target.apply(thisArg, args);
            return result + 1;
          },
        });
      }
      // 对嵌套对象递归处理
      if (typeof value === 'object' && value !== null) {
        return createResultAddOneProxy(value);
      }
      return value;
    },
  });
};

// 测试嵌套场景
const nestedObj = {
  math: {
    add: (a: number, b: number) => a + b,
    subtract: (a: number, b: number) => a - b,
  },
  constant: 100,
};

const nestedProxy = createResultAddOneProxy(nestedObj);
console.log(nestedProxy.math.add(2, 3)); // 输出 6(2+3+1)
console.log(nestedProxy.math.subtract(10, 4)); // 输出 7(10-4+1)
console.log(nestedProxy.constant); // 输出 100(非函数属性不受影响)

核心逻辑说明

  1. 利用对象Proxy的get陷阱拦截所有属性访问
  2. 当访问到函数类型的属性时,返回一个被Proxy包装的函数
  3. 在函数的apply陷阱中,执行原函数并对结果加1后返回
  4. 非函数属性和嵌套对象分别做直接返回和递归处理,保证原有逻辑不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:20:42