【问题标题】:Export class and instanciate it immediately on import导出类并在导入时立即实例化
【发布时间】:2016-01-22 18:14:02
【问题描述】:

我在 NodeJS 4 中有一个 ES6 类:

vehicule.js

"use strict";
class Vehicule {
  constructor(color) {
    this.color = color;
  }
}
module.exports = Vehicule;

当我需要在另一个文件中实例化时,我发现自己正在这样做:

var _Vehicule = require("./vehicule.js");
var Vehicule = new _Vehicule();

我是 nodeJs 的新手,有没有办法在一行中做到这一点,或者至少以一种更易读的方式?

【问题讨论】:

  • 我认为这是正确的做法。
  • 实例名称通常是小写的,所以使用import Vehicle from …const vehicle = new Vehicle();
  • 是的,你可以这样做:var vehicle = new (require("…"))() 但你应该问自己,当你真正将它用作单例时,你是否真的想要一个类。
  • @Bergi 我实际上将我的类用作数据库访问的单例工厂(因此需要一个类,以便我可以拥有一个可以扩展的基础工厂)。 “车辆”只是一个例子。我想我会选择 module.exports = new Vehicule();因为它是可读且单例的,除非你告诉我这是个坏主意
  • 不,你不需要一个类,这样你就有一个可以扩展的工厂。远离以课堂的方式思考一切。工厂只是一个函数,单例只是一个对象。也不需要继承。

标签: node.js class module require


【解决方案1】:

一个类确实应该被许多对象重用。所以你应该要求类本身:

var Vehicule = require("./vehicule.js");

然后从中创建对象:

var vehicle1 = new Vehicule('some data here');
var vehicle2 = new Vehicule('other data here');

通常类以大写字母开头,类的实例(对象本身)以小写字母开头。

如果你只想要一个对象的“类”,你可以创建一个内联对象:

var vehicle = {
    myProperty: 'something'
};

module.exports = vehicle;

//in some other file
var vehicle = require('vehicle');

如果你真的,真的想在一行中做到这一点,你可以这样做:

var vehicle = new (require('vehicle'))('some constructor data here');

但不建议这样做。几乎从来没有。

【讨论】:

    【解决方案2】:

    如果你真的想在一行中做到这一点:

    var Vehicule = new (require('./vehicule'))('red');
    

    但出于@ralh 提到的相同原因,我个人更喜欢两行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      相关资源
      最近更新 更多