我在 Adonis 中导入了一些类
const User = use('App/Models/User')
const Orders = use('App/Models/Orders')
我希望能够动态访问上述类之一。我的意思是一个变量将保存我想要访问的类。该变量将通过用户的 API 调用来填充。
let className = 'Orders'
如何使用 className
变量访问 Orders 类。
我已经尝试过
[className].query().where('orderNumber','123').fetch()
但是这似乎不起作用。
最佳答案
创建一个名称 -> 类
映射:
const classes = {
__proto__: null, // to avoid people being able to pass something like `toString`
Users,
Orders,
};
// or if you don't want to use __proto__
const classes = Object.assign(
Object.create(null),
{Users, Orders}
);
并使用classes[className]
访问正确的类。当然要验证该类是否存在。
I have tried
[className].query().where('orderNumber','123').fetch()
However that does not seem to work.
在此上下文中,[...]
表示数组文字,因此 [className]
仅创建一个包含 className
(在示例中为字符串)作为唯一元素的数组。
关于javascript - 使用字符串变量访问nodejs静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55305021/