我有一个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"
}
}
我希望example
内的other-module
函数能够了解foo
内的main-module
变量,即使它是在模块需要之后建立的。
other-module
运行时,foo
将不会是undefined
。但是,重点是,在我的example
函数运行时,foo
的值将为bar
。
上面的模式显然不起作用。我需要实施哪种设计模式?
答案 0 :(得分:2)
我不太熟悉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());
}
}
答案 1 :(得分:0)
foo值(字符串)将按值传递,因此在其他模块中为undefined
。您可以使用通过引用传递的选项对象:
var options = {},
someModule = require('other-module')(options);
options.foo = "bar";