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

如何在JavaScript中以编程方式获取getter方法的名称?

如何编程获取JavaScript中Getter方法的名称

你遇到的问题是:普通类方法可以通过Example.prototype.methodA.name直接获取方法名,但getter方法直接访问Example.prototype.methodB会触发它的执行,没法拿到对应的方法名称。要解决这个问题,你需要通过属性描述符来获取getter对应的函数,进而拿到它的名称。

基本解决方案

使用Object.getOwnPropertyDescriptors获取原型上的属性描述符,从描述符的get字段中提取函数名称:

class Example {
  methodA() {}
  get methodB() {}
}

// 获取普通方法名称
console.log('普通方法名称:', Example.prototype.methodA.name);

// 获取getter方法名称
const prototypeDescriptors = Object.getOwnPropertyDescriptors(Example.prototype);
console.log('Getter方法名称:', prototypeDescriptors.methodB.get.name);

适配Proxy场景的实现

针对你用Proxy处理类扩展、检测getter调用的需求,可以在Proxy的get陷阱中先获取属性描述符,判断当前属性是否为getter,同时自动获取它的方法名,避免硬编码属性名:

class Example {
  get methodB() {
    return 'getter返回值';
  }
}

const exampleProxy = new Proxy(Example.prototype, {
  get(target, propKey) {
    const propDescriptor = Object.getOwnPropertyDescriptor(target, propKey);
    // 判断当前属性是否是getter,且对应的get函数存在
    if (propDescriptor && typeof propDescriptor.get === 'function') {
      console.log(`检测到getter方法 ${propDescriptor.get.name} 被调用`);
    }
    // 正常返回属性值
    return Reflect.get(target, propKey);
  }
});

// 触发getter调用
exampleProxy.methodB;
// 控制台输出:检测到getter方法 methodB 被调用

这样即使后续重命名了getter方法,代码也不需要手动修改判断逻辑,会自动获取更新后的方法名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:40:43