[英]How to construct an imported class in Node.js?
I'm trying to make some discord bots, and I'm getting frustrated trying to use a class I created in another script.我正在尝试制作一些不和谐的机器人,但我在尝试使用我在另一个脚本中创建的类时感到沮丧。 The script in question looks like this:有问题的脚本如下所示:
// utils.js
class BotUtils {
constructor(param1, param2, ...) {
this.param1 = param1;
this.param2 = param2;
...
}
someMethod() {
doSomething;
}
}
module.exports = {BotUtils};
In my bot script, I have:在我的机器人脚本中,我有:
// bot.js
const botUtils = require('./BotUtils');
let utils = new BotUtils(param1, param2, ...);
And I get TypeError: BotUtils is not a constructor
我得到TypeError: BotUtils is not a constructor
I've also tried using new
but it doesn't work.我也尝试过使用new
但它不起作用。 I need to construct the class with the specific parameters.我需要用特定的参数构造类。 What's the correct way to do this?这样做的正确方法是什么?
You are exporting an object with the class BotUtils
as a property from your module.您正在从模块中导出一个BotUtils
类的对象作为属性。 To create an instance of the class, you need to reference the property ie要创建该类的实例,您需要引用该属性,即
let utils = new botUtils.BotUtils(param1, param2, ...);
If you want to export only the BotUtils
class then you can do so by removing the brackets如果您只想导出BotUtils
类,则可以通过删除括号来实现
module.exports = BotUtils;
Then when you require the module the class is what is returned, this is closer to your original code but with a small tweak然后,当您需要模块时,返回的就是类,这更接近您的原始代码,但稍作调整
const BotUtils = require('./utils');
Additionally, if you are using ES modules , this gets a lot easier with named exports此外,如果您使用ES 模块,使用命名导出会更容易
import { BotUtils } from './utils'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.