我有一个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());
}
}
foo值(字符串(将通过值传递,因此它在其他模块中是undefined
。您可以使用通过引用传递的选项对象:
var options = {},
someModule = require('other-module')(options);
options.foo = "bar";