سؤال

I have a namespace: Foo.Bar.Baz within which I have the Qux class. These were defined using the revealing module pattern:

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));

Now, in a separate file, I want to add the Quux class to this namespace. How do I do that? When I use the same pattern as above, it is ignored, as I guess the one is overwriting the other.

هل كانت مفيدة؟

المحلول 2

Figured it out: as expected, the second file's module was overwriting the first as soon as it was loaded.

In each file, use this structure:

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

Use the same structure for the other files (which contain the same module but with different classes). It won't matter which is defined first.

نصائح أخرى

Since you've already assigned an object to Baz, you just need to create a new property:

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

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

Of course Quux doesn't have access to the private members of Qux, is that the issue?

Edit

If you want to pass in the object reference, you can do:

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

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

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

The two approaches are functionally equivalent.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top