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

如何在实例化前获取JavaScript类的所有字段与方法名称

如何在实例化JavaScript类之前获取所有字段与方法名称?

你现在的问题是:用Object.getOwnPropertyNames(Demo.prototype)只能拿到类的方法名,想要在实例化类之前,获取包括field1、field2这类实例字段和method1方法在内的所有成员名称,预期得到['field1','field2','method1']。

问题原因

类里的实例字段(就是直接在类体里赋值的field1 = 1这种),是在类被实例化的时候才会被添加到实例对象上,并不会挂载到类的prototype原型上,所以直接访问原型只能拿到定义在原型上的方法。

解决方法

方法一:解析类的源代码(无需实例化)

通过类名.toString()获取类的源码文本,再用正则匹配出字段和方法名:

class Demo{
    field1 = 1;
    field2 = 2;
    
    method1(){
        return this.field1 + this.field2;
    }
}

function getClassAllMembers(cls) {
    const classSource = cls.toString();
    // 匹配实例字段:字段名 = 任意内容;
    const fieldMatchRegex = /(\w+)\s*=\s*[^;]+;/g;
    // 匹配方法:方法名() { ... }
    const methodMatchRegex = /(\w+)\s*\([^)]*\)\s*{/g;

    const allMembers = [];
    let matchResult;

    // 提取字段名
    while ((matchResult = fieldMatchRegex.exec(classSource)) !== null) {
        allMembers.push(matchResult[1]);
    }

    // 提取方法名,排除constructor(如果有定义的话)
    while ((matchResult = methodMatchRegex.exec(classSource)) !== null) {
        if (matchResult[1] !== 'constructor') {
            allMembers.push(matchResult[1]);
        }
    }

    return allMembers;
}

console.log(getClassAllMembers(Demo)); // 输出: ['field1', 'field2', 'method1']

⚠️ 注意:这种方法依赖类代码的格式,如果类源码被压缩、混淆或者写法不规范,正则可能匹配失败。

方法二:创建临时实例(更可靠,但会实例化类)

如果类的构造函数没有副作用(比如不会发起请求、修改全局状态),可以创建一个临时实例来获取字段,再结合原型上的方法:

class Demo{
    field1 = 1;
    field2 = 2;
    
    method1(){
        return this.field1 + this.field2;
    }
}

function getAllClassMembers(cls) {
    // 创建临时实例
    const tempInstance = new cls();
    // 获取实例自身的字段名
    const instanceFields = Object.getOwnPropertyNames(tempInstance);
    // 获取原型上的方法名,排除constructor
    const prototypeMethods = Object.getOwnPropertyNames(cls.prototype).filter(name => name !== 'constructor');
    // 合并结果
    return [...instanceFields, ...prototypeMethods];
}

console.log(getAllClassMembers(Demo)); // 输出: ['field1', 'field2', 'method1']

如果类的构造函数有副作用,这个方法需要谨慎使用,或者可以在临时实例使用后做清理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:47:20