title: OO Javascript constructor pattern: neo-classical vs prototypal
body: <p>I watched <a href="http://google-code-updates.blogspot.com/2009/03/doug-crockford-javascript-good-parts.html" rel="noreferrer">a talk by Douglas Crockford on the good parts in Javascript</a> and my eyes
  were opened.  At one point he said, something like, "Javascript is the only language where good programmers believe they can use it effectively, without learning it."  Then I realized, <em>I am that guy.</em> </p>
  
  <p>In that talk, he made some statements that for me, were pretty surprising and insightful. For example, JavaScript is the most important programming language on the planet.  Or it is the most popular language on the planet.  And, that it is broken in many serious ways.  </p>
  
  <p>The most surprising statement he made, for me, was "new is dangerous".  He doesn't use it any more.  He doesn't use <code>this</code> either. </p>
  
  <p>He presented an interesting pattern for a constructor in Javascript, one that allows for private and public member variables, and relies on neither <code>new</code>, nor <code>this</code>.  It looks like this:  </p>
  
  <pre><code>// neo-classical constructor
  var container =  function(initialParam) {
      var instance = {}; // empty object 
  
      // private members
      var privateField_Value = 0;
      var privateField_Name = "default";
  
      var privateMethod_M1 = function (a,b,c) {
          // arbitrary
      }; 
  
      // initialParam is optional
      if (typeof initialParam !== "undefined") {
          privateField_Name= initialParam;
      }
  
      // public members
      instance.publicMethod = function(a, b, c) {
          // because of closures,
          // can call private methods or
          // access private fields here. 
      };
  
      instance.setValue = function(v) {
          privateField_Value = v;
      };
  
      instance.toString = function(){
          return "container(v='" + privateField_Value + "', n='" + privateField_Name + "')";
      };
  
      return instance;
  }
  
  
  // usage
  var a = container("Wallaby");
  WScript.echo(a.toString()); 
  a.setValue(42);
  WScript.echo(a.toString()); 
  
  var b = container();
  WScript.echo(b.toString()); 
  </code></pre>
  
  <p><strong>EDIT</strong>: code updated to switch to lowercase class name.</p>
  
  <p>This pattern has evolved from <a href="http://www.crockford.com/javascript/private.html" rel="noreferrer">Crockford's earlier usage models</a>.</p>
  
  <p><em>Question:</em> Do you use this kind of constructor pattern?  Do you find it understandable?  Do you have a better one?</p>