title: Closures vs. classes for encapsulation?
body: <p>I'm new to JS (from C++/etc), and it's just occurred to me that closures seem to be a simpler and more convenient way to handle encapsulation than classes. This code seems to give a simple way to handle encapsulation:</p>
  
  <pre><code>function addProperty(o) {
     var value;
  
     o["get"] = function()  { return value; }
     o["set"] = function(v) { value = v; }
  }
  
  // create two independent objects which are instances of pseudo-class 'addProperty',
  // which each have their own version of a set of local fields, and methods that
  // operate on those fields:
  var a = {};
  addProperty(a);
  var b = {};
  addProperty(b);
  </code></pre>
  
  <p>If you just want a class to handle encapsulation (in C++, I find this is most of the time), is there any good reason to use a JS class instead of a closure? The code above seems to me to be more intuitive and compact than JS classes. No constructors, prototypes, or excessive use of 'this'. You also get the benefit that you must explicitly declare local fields, instead of hoping that you don't make any typos in your constructor.</p>
  
  <h2>EDIT</h2>
  
  <p>Ok, I'll just clarify. Seems like the 'class' word gets some backs up. A "class", to me anyway, is an extension of the type concept, and JS doesn't qualify on that front, but I can do various class-y things with what my book (Flanagan) spends 50 pages calling classes. Sort of.</p>
  
  <p>Anyway, the real question is this: I'm using jQuery tabs on my first web app. I noticed yesterday that this doesn't work, because my JS code doesn't keep any private state for each tab. When I swap between tabs, the dynamic/mouse parts of my code no longer work properly.</p>
  
  <p>So, what's the best way to introduce private state into the app? Most of the code is safe, but everything that handles dynamic behaviour needs some way to encapsulate per-tab local state. With a C++ background, the obvious answer to me is to write a class that defines the dynamic parts of a tab, and to instantiate a new 'tab' object each time a tab is created. What I'm finding it difficult to get my head around is whether JS pseudo-classes actually make any sense here, or whether I should extend the code above.</p>
  
  <p>Just read the module patterns link from Jonathan, and it now seems to me to be that that may be the answer. </p>
  
  <p>Thanks.</p>