title: Passing a window object into Javascript namespace
body: <p>I'm trying to better understand namespacing in javascript and  found an example of a javascript Immediately-invoked Function Expression that is taking the window object as a parameter. Here is the code from it:</p>
  
  <pre><code>var CG = CG || {};
  CG.main = (function(window) {
      var FOCAL_LENGTH = 8.0;
      var context, width, height, startTime;
  
      var init = function() {
          var element = document.getElementById("canvas1");
          context = element.getContext("2d");
  
          width = element.width;
          height = element.height;
  
          startTime = (new Date()).getTime() / 1000.0;
          tick();
      }
  
  var original_onload = window.onload || function() {};
      window.onload = function() {
          original_onload();
          CG.main.init();
      }
      return {
          init: init,
          draw: draw_shape,
          clear: clear_canvas
      };
  }(window));
  </code></pre>
  
  <p>At the end of the namespace definition, there is a line with window in parenthesis which I am confused as to the functionality of. I think that the purpose of adding the parameter of window to the end of the definition is to bind the global window variable to the namespace which will then add different properties to the window, but I can't really be sure. </p>
  
  <p>In another example there is a random variable name passed into the definition of a namespace, and at the end of the namespace definition, the actual name of the namespace is passed as a parameter:</p>
  
  <pre><code>var namespace = namespace || {};
  // here a namespace object is passed as a function
  // parameter, where we assign public methods and
  // properties to it
  (function( o ){
      o.foo = "foo";
      o.bar = function(){
          return "bar";
      };
  })(namespace);
  console.log(namespace);
  </code></pre>
  
  <p>So there are really a couple of questions here:</p>
  
  <ol>
  <li><p>What is the functionality of passing a parameter at the end of the namespace definition?</p></li>
  <li><p>If my intuition for how this all works is incorrect, what is the general structure for this kind of namespace creation javascript?</p></li>
  </ol>
  
  <p>Clearly I'm very new to this so any help would be appreciated, thanks.</p>