我有一个 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
:
// other-module.js
module.exports = function (foo) {
function example() {
console.log(foo);
// > "bar"
}
}
我希望 other-module
中的 example
函数能够识别 main-module 中的
,即使它是在需要模块之后建立的。foo
变量
当other-module
运行时,foo
不会是undefined
。然而,关键是当我的 example
函数运行时,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());
}
}
关于JavaScript 设计模式 : Injecting a dependency that is not yet created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15078811/