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

如何使用装饰器让JSON.stringify输出对象的getter?

用纯装饰器让JSON.stringify输出Getter的解决方案

嘿,我懂你要的是纯装饰器方案——毕竟手动用Object.defineProperty设置enumerable: true虽然能解决问题,但用装饰器复用性更强也更优雅。咱们直接上能生效的代码:

1. 写一个专门处理Getter可枚举性的属性装饰器

这个装饰器的核心就是拿到类中getter的属性描述符,把enumerable改成true,和你手动做的逻辑完全一致,只不过用装饰器封装了起来:

// 定义装饰器:将目标getter设为可枚举
function EnumerableGetter(target: any, propertyKey: string) {
  const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
  if (descriptor && descriptor.get) {
    // 保留原getter逻辑,仅修改可枚举性
    descriptor.enumerable = true;
    Object.defineProperty(target, propertyKey, descriptor);
  }
}

2. 在你的类Getter上直接用这个装饰器

class DemoClass {
  private _privateData = "我是私有数据,但getter能访问到";

  @EnumerableGetter
  get exposedData() {
    return this._privateData;
  }
}

// 测试效果
const demo = new DemoClass();
console.log(JSON.stringify(demo)); 
// 输出:{"exposedData":"我是私有数据,但getter能访问到"}

为啥这个装饰器能生效?

默认情况下,类中定义的getter的属性描述符里enumerable是false,这也是JSON.stringify忽略它的原因。这个装饰器就是精准修改了这个属性,让getter变成可枚举的,自然就能被JSON.stringify捕获到了。

小提示(TypeScript用户看这里)

如果你用TypeScript,得确保tsconfig.json里开启了装饰器的支持:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

要是你需要处理静态getter,逻辑也差不多,只需要调整装饰器里的目标对象处理逻辑就行,这个方案完全符合你要的纯装饰器、不用toJSON的要求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:00:37