如何在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
相关产品推荐
相关产品推荐

