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

时间:2013-02-25 23:52:36

标签: 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

// 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

上面的模式显然不起作用。我需要实施哪种设计模式?

2 个答案:

答案 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";