JavaScript设计模式:注入尚未创建的依赖项
我有一个CommonJS模块:JavaScript设计模式:注入尚未创建的依赖项,javascript,design-patterns,dependency-injection,commonjs,Javascript,Design Patterns,Dependency Injection,Commonjs,我有一个CommonJS模块: // main-module module.exports = function () { var foo, someModule = require('other-module')(foo); // A value is given to foo after other-module has been initialised foo = "bar"; } 如您所见,这需要其他模块: // other-module.js module.
// main-module
module.exports = function () {
var foo,
someModule = require('other-module')(foo);
// A value is given to foo after other-module has been initialised
foo = "bar";
}
如您所见,这需要其他模块
:
// other-module.js
module.exports = function (foo) {
function example() {
console.log(foo);
// > "bar"
}
}
我希望其他模块中的示例
函数
能够了解主模块
中的foo
变量,即使它是在需要模块后建立的
当其他模块
运行时,foo
将不会未定义
。然而,关键是,当我的示例
函数运行时,foo
将被赋予bar
的值
上述模式显然不起作用。我需要实现什么设计模式?我对CommonJS不太熟悉,因此这可能不是实现它的惯用方法,但使用函数而不是变量应该可以:
// main-module
module.exports = function () {
var foo,
someModule = require('other-module')(function() { return foo; });
foo = "bar";
}
// other-module.js
module.exports = function (fooFn) {
function example() {
console.log(fooFn());
}
}
foo值(一个字符串)将通过值传递,因此它在其他模块中是未定义的。您可以使用通过引用传递的选项对象:
var options = {},
someModule = require('other-module')(options);
options.foo = "bar";
@OliverJosephAsh更改
options={“foo”:“bar”}
tooptions.foo='bar'代码>会的。谢谢@MattBall,你说得对。如果我们给选项分配一个新值,我们会遇到与按值传递字符串时相同的问题-因此我们需要保持选项
引用相同。