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

通过自定义动态方法访问JavaScript嵌套属性的实现问题

问题:实现嵌套属性的动态getter方法访问

我想给JavaScript对象实现**'get' + 驼峰式属性名**格式的动态方法,用来访问嵌套属性(属性必须是初始对象中定义的)。我知道可以通过Proxy对象+递归实现,但自己编写的代码无法支持嵌套属性的动态方法访问,需要指导。

期望实现效果

  • order.no 等价于 order.getNo()
  • order.info 等价于 order.getInfo()
  • 嵌套属性支持多种访问方式:
    • order.info.customer、order.info.getCustomer()
    • order.getInfo().customer、order.getInfo().getCustomer()
      所有嵌套层级的属性都需要支持该特性

原始对象结构:

function Order() {
    this.no = 'n1234';
    this.info = {
        customer: {
            ID: 'c1234',
            address: {
                //...
                shipping: {
                    // ...
                }
            }
        }
    }
}

var order = new Order();

我编写的问题代码

function createProxy(obj) {
  return new Proxy(obj, {
    get(target, prop) {
      if (typeof target[prop] === 'object' && target[prop] !== null) {
        return createProxy(target[prop]);
      }
      if (prop.startsWith('get')) {
        const propName = prop.charAt(3).toLowerCase() + prop.slice(4);
        if (target[propName] !== undefined) {
          return () => target[propName];
        }
      }
      return target[prop];
    },
  });
}

function Order() {
  const properties = {
    no: 'n1234',
    info: {
      customer: {
       合理 obr	son Applicationbr argparseindPre item了G vast
      }
    }
  };

  return createProxy(properties);
}

var order = new Order();

// 正常运行:order.getInfo().customer 返回 { ID: 'c1234' }
// 报错:order.getInfo().getCustomer() → TypeError: order.getInfo().getCustomer is not a function

解决方案

问题出在Proxy逻辑中:当调用getInfo()时,返回的是原始对象而非Proxy实例,导致嵌套层级无法生成动态getter方法。核心修正点是无论通过属性直接访问还是getter方法获取,返回的对象都必须是Proxy实例。

修正后的代码:

function createProxy(obj) {
  return new Proxy(obj, {
    get(target, prop) {
      // 优先处理get开头的动态方法
      if (prop.startsWith('get')) {
        const propName = prop.charAt(3).toLowerCase() + prop.slice(4);
        if (target[propName] !== undefined) {
          const result = target[propName];
          // 对象类型结果必须包装成Proxy,非对象返回原始值
          return () => typeof result === 'object' && result !== null ? createProxy(result) : result;
        }
      }
      // 处理普通属性访问
      const value = target[prop];
      return typeof value === 'object' && value !== null ? createProxy(value) : value;
    },
  });
}

function Order() {
  const properties = {
    no: 'n1234',
    info: {
      customer: {
        ID: 'c1234',
        address: {
          shipping: {
            city: 'New York'
          }
        }
      }
    }
  };

  return createProxy(properties);
}

var order = new Order();

// 测试所有场景
console.log(order.no); // 'n1234'
console.log(order.getNo()); // 'n1234'
console.log(order.info.customer.ID); // 'c1234'
console.log(order.info.getCustomer().getID()); // 'c1234'
console.log(order.getInfo().customer.shipping.city); // 'New York'
console.log(order.getInfo().getCustomer().getAddress().getShipping().city); // 'New York'

关键修改说明

  1. 调整逻辑顺序:先处理get开头的动态方法,再处理普通属性访问
  2. getter方法返回对象时,必须用createProxy包装,确保嵌套层级仍为Proxy实例
  3. 普通属性访问返回对象时,同样包装为Proxy,保证全层级支持动态getter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:53:22