首页 > 解决方案 > 如何在 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')

标签: javascriptnode.js

解决方案


您必须使用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

推荐阅读