同一命名空间中的多个“类”,但在单独的文件中

时间:2013-03-13 23:19:27

标签: javascript module-pattern revealing-module-pattern

我有一个名称空间:Foo.Bar.Baz我有Qux类。这些是使用揭示模块模式定义的:

Foo.Bar.Baz = (function ($) {  // the namespace/module

  function Qux() {             // the Qux "class" is contained in this namespace
  // ...
  }

  Qux.prototype.doStuff = function() {
  // ...
  }

  return {                     // public exports from this namespace
    Qux: Qux
  };

}(jQuery));

现在,在一个单独的文件中,我想将Quux类添加到此命名空间。我怎么做?当我使用与上面相同的模式时,它会被忽略,因为我猜这个模式会覆盖另一个模式。

2 个答案:

答案 0 :(得分:1)

由于您已经将对象分配给Baz,因此您只需要创建一个新属性:

Foo.Bar.Baz.Quux = (function() {
    function private() {}
    var privateVar = 'whatever';

    return function() {
        // access private and privateVar
    };
}());

当然Quux无权访问Qux的私有成员,这是问题吗?

修改

如果要传递对象引用,可以执行以下操作:

(function(module) {
    function private() {}
    var privateVar = 'whatever';

    module.Qux = function() {
      // whatever
    };

    module.Quux = function() {
      // different whatever
    };
}(Foo.Bar.Baz));

这两种方法在功能上是等价的。

答案 1 :(得分:1)

想出来:正如预期的那样,第二个文件的模块在加载后立即覆盖了第一个文件。

在每个文件中,使用以下结构:

Foo.Bar.Baz = (function (module, $) { // redefine existing module

  function Qux() {                    // add Qux "class" to it
  // ...
  }


  var exports = {                     // revealing module pattern: define exports
    Qux: Qux,
    // etc.
  };
  $.extend(module, exports);          // merge modules
  return module;

}(Foo.Bar.Baz, jQuery));              // import existing module, and anything else

对其他文件使用相同的结构(包含相同模块但具有不同类的文件)。首先定义哪个无关紧要。

相关问题