[英]Node.js: exporting class/prototype vs. instance
As I do most of my programming in Java, I find it compelling to export a class in a Node.js module instead of an object instance, eg:由于我在 Java 中进行大部分编程,我发现在 Node.js 模块中导出类而不是对象实例是很有吸引力的,例如:
class Connection {
constructor(db) {
this.db = db;
}
connect(connectionString) {
this.db.connect(connectionString);
}
}
exports.Connection = Connection;
Since doing this would require instantiating the class multiple times across dependent modules, I still need to export an already existing instance for use in the rest of the production code.由于这样做需要跨依赖模块多次实例化该类,因此我仍然需要导出一个已经存在的实例以用于其余的生产代码。 I do it in the same module:我在同一个模块中执行此操作:
exports.connection = new Connection(require("mongoose"));
This allows for some testability, as the real dependency can be swapped in a test:这允许一些可测试性,因为可以在测试中交换真正的依赖关系:
const Connection = require("./connection").Connection;
describe("Connection", () => {
it("connects to a db", () => {
const connection = new Connection({connect: () => {}});
// ...
});
});
This approach works, but it has a strange feel to it as I'm mixing two patterns here: exporting a prototype (for unit tests) and an instance (for the production code).这种方法有效,但它有一种奇怪的感觉,因为我在这里混合了两种模式:导出原型(用于单元测试)和实例(用于生产代码)。 Is this acceptable?这可以接受吗? Should I continue with this or change to something different?我应该继续这样做还是换成不同的东西? If so, what is the preferred pattern?如果是这样,首选模式是什么?
You're right, it's a bad coding style, but actually you can write a function which, depending on the received parameter, returns either the single instance (for the whole application), or the class itself (for testing).你是对的,这是一种糟糕的编码风格,但实际上你可以编写一个函数,根据接收到的参数,返回单个实例(用于整个应用程序)或类本身(用于测试)。 Something like this:像这样的东西:
class MyClass() {}
const instance = new MyClass();
function getInstanceOrClass(isTesting) {
if(isTesting) {
return MyClass;
} else {
return instance;
}
}
exports.getInstanceOrClass = getInstanceOrClass;
// in other files
const getInstanceOrClass = require('./yourFileName');
const classSingletonInstance = getInstanceOrClass();
// in test files
const getInstanceOrClass = require('./yourFileName');
const MyClass = getInstanceOrClass(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.