简体   繁体   English

通过带有Node.js中构造函数的模块公开多个对象

[英]Expose multiple objects through module with constructor in nodejs

I created a module in nodejs where I wish to expose it's constants too. 我在nodejs中创建了一个模块,在这里我也希望公开它的常量。 But this particular module contains a dependency which is provided at construction time ie dependency injection. 但是此特定模块包含一个在构建时提供的依赖项,即依赖项注入。

this is module1 这是module1

const STORE_TYPE = {
  STORE1: 1,
  STORE2: 2
};

function service(dependency1) {
  this.dep = dependency1;
}

service.prototype.doSomething = function(param1, store) {
  if (STORE_TYPE.STORE1 == store) {
    return this.dep.get(param1);
  } else {
    return "something";
  }
};

module.exports = service;

I'm using module1 here: 我在这里使用module1:

var dep = require('./dep');
var dep1 = new otherService(dep);
var service = require('./service')(dep1);

function getData() {
  return service.doSomething(id, /*this is module1 constant*/1);
}

How do I refere to module1's constants if module1 has a constructor. 如果module1具有构造函数,如何引用module1的常量。

I don't wish to add separate method only to create service since callee needs to perform multiple steps. 我不希望仅添加单独的方法来创建服务,因为被调用者需要执行多个步骤。

Try this: 尝试这个:

service.js

exports.STORE_TYPE = {
  STORE1: 1,
  STORE2: 2
};

exports.service = function service(dependency1) {
  this.dep = dependency1;
}

service.prototype.doSomething = function(param1, store) {
  if (STORE_TYPE.STORE1 == store) {
    return this.dep.get(param1);
  } else {
    return "something";
  }
};

Using that module 使用该模块

app.js

const service = require('./service').service;

const STORE_STYLE = require('./service').STORE_TYPE;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM