JavaScript设计模式:注入尚未创建的依赖项



我有一个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";

最新更新