Private namespaces for library sub-modules using prototype <p>I'm working on a large JavaScript UI module, think about something in the dimension of iScroll. For keeping the thing sane, I split the library up into several logical sub-modules (like: touch interaction, DOM interaction, etc.) that communicate with each other using a simple pubsub system.</p> <p>Each of these sub-modules has it's own namespace I use for storing variables. To enable several instances of the library running at the same time, the constructor includes some logic to copy every namespace that has been assigned to a 'toCopy' object directly into every new instance.</p> <p>The basic structure looks something like this:</p> <pre><code>// constructor function Constructor() { for (var key in this.toCopy) { // create a deep copy and store it inside the instance this[key] = utils.copyObj(this.toCopy[key]); } } Constructor.prototype.toCopy = {} // sub-module #1 Constructor.prototype.toCopy._module1Namespace = {} Constructor.prototype._privateFn = function() { /** do stuff within this._module1Namespace or send events */ } Constructor.prototype._privateFn = function() { /** do stuff within this._module1Namespace or send events */ } // sub-module #2 Constructor.prototype.toCopy._module2Namespace = {} Constructor.prototype._privateFn = function() { /** do stuff with this._module2Namespace or send events */ } Constructor.prototype._privateFn = function() { /** do stuff with this._module2Namespace or send events */ } </code></pre> <p>My problem: I really dislike having to expose the namespace of each sub-module to the rest of the library. Although I'm disciplined enough not to access the namespace of sub-module #1 within a function of sub-module #2, I want it to be technically impossible.</p> <p>However, as several instances of the UI library have to run at the same time, I cannot put every sub-module inside a closure and define a private namespace inside this closure. This would result in every instance of the library accessing the same sub-module closure and therefore the same namespace.</p> <p>Also, putting everything inside the constructor instead of into the prototype would create a new set of functions for every new instance, which somehow contradicts the idea of a good library.</p> <p>My research hasn't brought up any useful patterns for this problem so far, I'm thankful for all suggestions.</p>