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

无法遍历JavaScript类的Prototype对象?求解决方法

问题分析与解决

先看你提供的代码:

class SomeClass {
  myFunction() {
    console.log('Hello, World');
  }
}

for (let obj in SomeClass.prototype) {
  console.log(obj);
}

问题原因

用class语法定义的类方法,会被挂载到类的原型对象上,但这些方法的可枚举性(enumerable)默认被设为false。而for...in循环仅会遍历对象的可枚举属性,所以你看不到任何输出内容。

解决方法

方法1:使用Object.getOwnPropertyNames()

这个方法可以获取对象的所有自有属性(包含不可枚举属性),再遍历输出:

class SomeClass {
  myFunction() {
    console.log('Hello, World');
  }
}

Object.getOwnPropertyNames(SomeClass.prototype).forEach(key => {
  console.log(key);
});

输出结果:

constructor
myFunction

方法2:过滤掉constructor属性

如果只需要获取自定义的类方法,不需要默认的constructor,可以添加过滤逻辑:

Object.getOwnPropertyNames(SomeClass.prototype)
  .filter(key => key !== 'constructor')
  .forEach(key => console.log(key));

输出结果:

myFunction

方法3:使用Reflect.ownKeys()

这个方法功能和Object.getOwnPropertyNames()类似,还能获取Symbol类型的属性:

Reflect.ownKeys(SomeClass.prototype).forEach(key => {
  console.log(key);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:40:33