简体   繁体   English

使用字符串变量访问Node.js静态方法

[英]Access nodejs static method using a string variable

I have imported a few classes in Adonis 我已经在阿多尼斯导入了几个课程

const User = use('App/Models/User')
const Orders = use('App/Models/Orders')

I want to be able to access one of the above classes dynamically. 我希望能够动态访问上述类之一。 By that I mean a variable will hold the class I want to access. 我的意思是,变量将保存我要访问的类。 The variable will be populated by via an API call from the user. 该变量将通过用户的API调用进行填充。

let className = 'Orders'

How to I use the className variable to access the Orders class. 如何使用className变量访问Orders类。

I have tried 我努力了

[className].query().where('orderNumber','123').fetch()

However that does not seem to work. 但是,这似乎不起作用。

Create a name -> class map: 创建一个name -> class映射:

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}
);

and access the right class with classes[className] . 并使用classes[className]访问正确的类。 Of course verify whether the class exists or not. 当然,请验证该类是否存在。


I have tried 我努力了

 [className].query().where('orderNumber','123').fetch() 

However that does not seem to work. 但是,这似乎不起作用。

In this context, [...] denotes an array literal, so [className] just creates an array containing className (which is a string in your example) as only element. 在这种情况下, [...]表示数组文字,因此[className]仅创建一个包含className (在您的示例中为字符串)作为唯一元素的数组。

Avoid converting the variable to a string at all. 完全避免将变量转换为字符串。 Just use: 只需使用:

let className = Orders;
className.query().where('orderNumber','123').fetch()

If the class is being instantiated by an API call, use a simple switch statement: 如果通过API调用实例化该类,请使用简单的switch语句:

let class;
switch (apiCall.name) {
    case 'orders':
        class = Orders;
        break;
    case 'users':
        class = Users;
        break;
    default:
        throw 'Invalid API Call';
}

class.query().where('orderNumber','123').fetch()

最简单的方法是eval(className).query().where('orderNumber','123').fetch() ,但是如果您想将值作为实际类检查是否存在,则可能应该实现开关或-else-if检查并分配className,仅在实际存在时调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM