【问题标题】:How do I use my JavaScript class in NodeJS如何在 NodeJS 中使用我的 JavaScript 类
【发布时间】:2020-03-03 01:05:42
【问题描述】:

我在 JavaScript 文件中有一个类

class engine
{
   constructor(a)
   {
      this._a = a;
   }

   foo = function()
   {
      console.log(this._a);
   }
}
module.exports.engine = engine;

然后在我的 NodeJS 文件中执行

const engine = require('./engine.js');

现在我的问题是,如何使用构造函数 new engine('bar') 从 NodeJS 文件中的类中调用 foo()

【问题讨论】:

  • 一些约定:类名以大写字母开头,因为这是类应该使用的。小写表示它是一个函数。此外,如果您使用this,则没有理由使用下划线。 this.a = a 在你的构造函数中,然后 console.log(this.a) 在你的 foo 中。最后,为什么使用实例字段语法foo = function() { ... } 而不是普通的类方法语法foo() { ... }?它只是一个类函数,就这样声明吧。
  • @Mike'Pomax'Kamermans - 下划线 - 我认为有/曾经有一个约定,以 _ 开头的“属性”是“私有”或其他东西(显然它们不是) -参考:stackoverflow.com/questions/4484424/…
  • 这只是in Python @JaromandaX的约定,JS中没有这样的约定,私有属性的提议使用#
  • @Mike'Pomax'Kamermans - 回溯很多年(我的意思是很多年),这绝对是 javascript 中的约定 - 我确实链接到了错误的帖子:p

标签: javascript node.js


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你应该像这样将文件导出为默认值

    module.exports = engine;
    

    而不是

    module.exports.engine = engine;
    

    在第二个示例中,您将文件导出为 {engine} 并且在导入时应导入为

    const {engine} = require('./engine.js');
    
    

    但是当您像第一个示例一样使用导出时,您可以像这样导出和导入

    // engine.js
    module.exports = engine;
    
    
    
    // index.js
    const engine = require('./engine.js');
    
    const myEngine = new engine('a'); 
    myEngine.foo(); // You can now use foo() method
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多