根据具体情况,这肯定是可以接受的。静态或原型someModule 属性会更高效,但另一方面,这需要在测试模拟后恢复它。
这种模式通常会变得很麻烦,在这种情况下 DI 容器可能更方便。在 Node 领域有很多,例如injection-js that was extracted from Angular DI.
在其最简单的形式中,它可以是一个纯粹的单例容器,它不会自行创建实例,而是将现有值(模块导出)存储在随机标记下:
class Container extends Map {
get(key) {
if (this.has(key)) {
return super.get(key);
} else {
throw new Error('Unknown dependency token ' + String(key));
}
}
set(key, val) {
if (key == null) {
throw new Error('Nully dependency token ' + String(key));
} else if (arguments.length == 1) {
super.set(key, key);
} else {
super.set(key, val);
}
}
}
const container = new Container;
可以直接从容器中注册和检索依赖项:
const foo = Symbol('foo');
container.set(foo, require('foo'));
container.set('bar', require('bar'));
container.set(require('baz'));
...
const { foo } = require('./common-deps');
class Qux {
constructor() {
this.foo = container.get(foo);
...
}
}
另外,注入器可以包含容器:
class DI {
constructor(container) {
this.container = container;
}
new(Fn) {
if (!Array.isArray(Fn.annotation)) {
throw new Error(Fn + ' is not annotated');
}
return new Fn(...Fn.annotation.map(key => this.container.get(key)));
}
call(fn) {
if (!Array.isArray(fn.annotation)) {
throw new Error(fn + ' is not annotated');
}
return fn(...fn.annotation.map(key => this.container.get(key)));
}
}
const di = new DI(container);
并在带注释的类和函数中处理 DI(关于注释,请参阅this explanation):
class Qux {
constructor(foo, bar) {
this.foo = foo;
...
}
}
Qux.annotation = [foo, 'bar', require('baz')];
quuxFactory.annotation = [require('baz')]
function quuxFactory(baz) { ... }
const qux = di.new(Qux);
const quux = di.call(quuxFactory);