JavaScript 设计模式 : Injecting a dependency that is not yet created

标签 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"
  }
}

我希望 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());
  }
}

关于JavaScript 设计模式 : Injecting a dependency that is not yet created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15078811/

相关文章:

php - 在以下项目中实现 S.O.L.I.D 域对象模型

c# - MVVM Light 按键注册界面

javascript - 分配和删除点击事件

javascript - Express.js 中的“router.get”与 'router.route.get'

design-patterns - 静态类型检查的设计模式

java - Spring在路径中找不到配置

java - 如何避免 Spring 中的 applicationContext.getBean ?

javascript - 验证输入标签中的最大金额 : (Aurelia)

javascript - 如何在单元测试中测试新缓冲区中创建的值

c++ - 为可能改变其内部属性的类选择设计模式