如何获取 JS 中构造函数类的参数数组?这是可能的?提前致谢。
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(Product.constructor.params);
//expected output = ['id', 'name', 'price', 'category', 'stock'];
受到 @Porter 答案和 @evolutionxbox 的启发,我认为一种可靠的方法是使用.match()
像这样:
class Product {
constructor(id, name, price, category, stock, unusedArgument) {
this.id = id;
this.name = name;
this.price = price;
this.category = category;
this.stock = stock;
}
}
class Noarguments {
constructor() {
}
}
// A function
function getClassContructorParams(obj){
let match = obj.toString().match(/constructor\((.+)\)/)
if(match && match[1]){
return match[1].split(",");
}
// If no match
return []
}
console.log(getClassContructorParams(Product))
/// Testing a class with no constructor arguments will return an empty array
console.log(getClassContructorParams(Noarguments))
我之前的答案是返回对象属性,这可能与构造函数中使用的参数不同......
现在使用.match()
将确保返回的内容确实是constructor
论据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)