Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript设计模式:注入尚未创建的依赖项_Javascript_Design Patterns_Dependency Injection_Commonjs - Fatal编程技术网

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

JavaScript设计模式:注入尚未创建的依赖项,javascript,design-patterns,dependency-injection,commonjs,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.js module.

我有一个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.js
module.exports = function (foo) {
  function example() {
    console.log(foo);
    // > "bar"
  }
}
我希望
其他模块中的
示例
函数
能够了解
主模块
中的
foo
变量,即使它是在需要模块后建立的

其他模块
运行时,
foo
将不会
未定义
。然而,关键是,当我的
示例
函数运行时,
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值(一个字符串)将通过值传递,因此它在其他模块中是未定义的。您可以使用通过引用传递的选项对象:

var options = {},
someModule = require('other-module')(options);

options.foo = "bar";

@OliverJosephAsh更改
options={“foo”:“bar”}
to
options.foo='bar'会的。谢谢@MattBall,你说得对。如果我们给选项分配一个新值,我们会遇到与按值传递字符串时相同的问题-因此我们需要保持
选项
引用相同。