javascript - 如何在 NodeJS 中使用我的 JavaScript 类
问题描述
我在 JavaScript 文件中有一个类
class engine
{
constructor(a)
{
this._a = a;
}
foo = function()
{
console.log(this._a);
}
}
module.exports.engine = engine;
然后在我的NodeJS文件中我做
const engine = require('./engine.js');
现在我的问题是,如何foo()
使用构造函数从 NodeJS 文件中的类调用new engine('bar')
?
解决方案
您必须使用new
关键字进行实例化
const engine = require('./engine.js');
const myEngine = new engine('Hello world!'); // Now myEngine is instance of engine class
myEngine.foo(); // You can now use foo() method
推荐阅读
- python - 我有这些词典。我应该使用什么命令来打印第二个中的“d”键?有个窍门
- reactjs - 如何在 React js 上删除满足特定条件的列表元素
- testing - 是否可以在 testcafe-browser-provider-saucelabs 中添加 iPad 参数“deviceOrientation”?
- c# - 如何以编程方式从动态 JObject 中删除属性
- c# - 实体框架 - SaveChanges 与事务
- php - 如何过滤 wordpress the_date() 和 get_the_date() 函数以仅显示帖子发布的年份
- .net-core - Abp中如何使用EfCore Code First将实体中的注解生成到数据库的字段描述中
- linux - 如何修复 java.sql.SQLNonTransientException:java.sql.SQLNonTransientException:null DSRA0010E:SQL 状态 = 08001,错误代码 = -1,639 错误
- macos - 是否有可能在 MacOS v < 11 上获得 Apple Developer Id
- javascript - 由于无法使用 app.listen,如何使用使用 npm create-react-app 制作的 React 应用程序实现 Express.js?