如何在JavaScript中获取类constructor构造函数的参数名组成的数组?
JavaScript获取类constructor参数名数组的实现方案
结论
该需求可实现,JavaScript原生无直接可用的API,可通过解析构造函数的源码字符串达成目标。
原有代码问题说明
你示例中Product.constructor.params的写法无法拿到结果:Product.constructor实际指向的是Function根构造函数,而非你定义的Product类的构造方法,且原生JS不存在params这个内置属性。
具体实现代码
通用工具函数
function getConstructorParams(clazz) { // 读取类的源码字符串 const classSource = clazz.toString(); // 正则匹配constructor后的参数列表 const paramsReg = /constructor\s*\(([^)]*)\)/; const matchResult = classSource.match(paramsReg); // 无显式constructor时返回空数组 if (!matchResult) return []; // 处理参数字符串,提取参数名 return matchResult[1] .split(',') .map(paramItem => { // 过滤默认值、解构符号、空格等多余内容 return paramItem.replace(/\s*=.*$/, '').replace(/[{[}\]]/g, '').trim(); }) .filter(paramName => paramName); }
测试效果
class Product { constructor(id, name, price, category, stock){ this.id = id; this.name = name; this.price = price; this.category = category; this.stock = stock; } }; console.log(getConstructorParams(Product)); // 输出:['id', 'name', 'price', 'category', 'stock']
注意事项
- 该方案依赖
Function.prototype.toString()的标准返回值,主流浏览器、Node.js环境均支持 - 如果代码经过压缩混淆,原参数名会被替换为短字符,此时拿到的结果不符合预期
- 若构造函数使用了复杂解构、剩余参数等特殊写法,可根据实际场景调整正则匹配规则
- 未显式定义constructor的类调用该方法会返回空数组
内容的提问来源于stack exchange,提问作者sonEtLumiere
相关产品推荐
相关产品推荐

