title: Module pattern- How to split the code for one module into different js files?
body: <p>For the module pattern, I'm doing something like:</p>
  
  <pre><code>(function(namespace) {
      // tons of code
      // blabla
  })(window.myGlobalNamespace);
  </code></pre>
  
  <p>How do I split the code? I can think of a few ways, like use a hierachy of namespaces, or expand the object outside by <code>window.myGlobalNamespace.additionalFunc = function () {//blabla}</code>. What are the other ways? What are the pros and cons? Which one is considered better practice?</p>
  
  <p>Both of the two answers suggest RequireJS. Can you please explain how RequireJS can solve these problems:</p>
  
  <p>first.js:</p>
  
  <pre><code>(function(context) {
      var parentPrivate = 'parentPrivate';
  })(window.myGlobalNamespace);
  </code></pre>
  
  <p>second.js:</p>
  
  <pre><code>(function(context) {
      this.childFunction = console.log('trying to access parent private field: ' + parentPriavte);
  }(window.myGlobalNamespace.subNamspace);
  </code></pre>
  
  <p>main.js:</p>
  
  <pre><code>window.myGlobalNamespace.subNamspace.childFunction(); // doesn't work
  </code></pre>
  
  <p>And people can do</p>
  
  <pre><code>window.myGlobalNamespace.subNamspace.childFunction = function() {alert("a new function");}
  </code></pre>
  
  <p>to change my code's behaviour!</p>
  
  <p>Here, there are two problems:</p>
  
  <ol>
  <li><p>We can't have a field that's accessible by child but not to outside public (i.e. protected). Is there any way to achieve that?</p></li>
  <li><p>If not, meaning if we wanteparentPrivate to be accessible, we need to make it public. Then the user will be able to modify it!</p></li>
  </ol>
  
  <p>What's more, all the public functions can be altered and replaced. I don't want that to happen.</p>
  
  <p>I don't see how RequireJS solves these problems. Can someone shed some light?</p>