支持相互依赖的javascript模块模式

标签 javascript design-patterns

似乎使用下面的javascript模块模式,不可能有相互依赖的模块:

var AA = (function(module, BB){
  module.sayHello = function(){
    alert("AA: hello!");
  };
  module.pokeYourFriend = function(){
    BB.sayHello();
  };
  return module;
})(AA || {}, BB);

var BB = (function(module, AA){
  module.sayHello = function(){
    alert("BB: hello!");
  };
  module.pokeYourFriend = function(){
    AA.sayHello();
  };
  return module;
})(BB || {}, AA);


> AA.pokeYourFriend();
*TypeError: Cannot call method 'sayHello' of undefined*

以上失败,因为 AA 创建时 BB 不存在。

是否有一种模式允许这样做,或者应该禁止相互依赖?

最佳答案

AABB 的RHS 值是函数表达式,它们按自上而下的顺序求值(这是Javascript 中的正常顺序)。因此,在定义 BB 之前,您不能使用 BB

您可以使用“构造函数”来创建这些模块并为其分配名称(“AA”或“BB”),而不是 self 调用:

var create = (function(name) {
   var _friend = null;
   var _name = name;

   return {
      sayHello: function() {
         alert(_name + ": hello!");
      },
      pokeYourFriend: function() {
         if(_friend != null) {
            _friend.sayHello();
         }
      },
      setFriend: function(friend) {
         _friend = friend;
      }
   };
});

var AA = create("AA");
var BB = create("BB");

AA.setFriend(BB);
BB.setFriend(AA);

AA.pokeYourFriend(); //alerts "BB: hello!"
BB.pokeYourFriend(); //alerts "AA: hello!"

关于支持相互依赖的javascript模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749690/

相关文章:

javascript - 检测浏览器是否为 IE 7 或更低版本?

javascript - <%= 某事 %> 是什么?

ios - 在 swift 测试用例中注入(inject)单例 objective-c 类的依赖项

javascript - R Shiny 数据表: prevent deselection of an already selected row when you click on it again

javascript - express 服务器 : Error: Requested Range Not Satisfiable

javascript - beforeCreate 函数没有按顺序执行

java - 如果无代码 : is it just an intellectual challenge or is it concretely useful?

c# - 具有依赖注入(inject)设计的处理程序工厂

c# - Switch 语句的替代方法

java - 我什么时候应该使用新类而不是添加新字段(作为状态)?