title: Templates for JavaScript methods?
body: <p>I recently found a document by Mike Bostock, <a href="http://bost.ocks.org/mike/chart/#reconfiguration" rel="nofollow noreferrer">Towards Reusable Charts</a>, which describes some conventions for encapsulating reusable charts in <a href="http://d3js.org/" rel="nofollow noreferrer">D3</a>. Note however that the question isn't just about D3 but rather creating methods for JavaScript objects dynamically.</p>
  
  <p>His proposal includes the following snippet:</p>
  
  <pre><code>function chart() {
    var width = 720, // default width
        height = 80; // default height
  
    function my() {
      // generate chart here, using `width` and `height`
    }
  
    my.width = function(value) {
      if (!arguments.length) return width;
      width = value;
      return my;
    };
  
    my.height = function(value) {
      if (!arguments.length) return height;
      height = value;
      return my;
    };
  
    return my;
  }
  </code></pre>
  
  <p>This is all fine but what I am immediately wondering once I started adding more chart properties than just <code>width</code> and <code>height</code> to it is whether the common parts of these "property accessor functions" could be factored out somehow.</p>
  
  <p>I am imagining some method to dynamically register a property like this:</p>
  
  <pre><code>my.addProperty(propName) {
    my[propName] = function (value) {
                     if (!arguments.length) return getPrivateVar(propName);
                     setPrivateVar(propName, value);
                     return my;
                   };
  }
  </code></pre>
  
  <p>So I could then simply do </p>
  
  <pre><code>my.addProperty('width');
  my.addProperty('height');
  </code></pre>
  
  <p>to achieve the same result as the <code>my.width =</code> and <code>my.height =</code> statements from the code above.</p>
  
  <p>Is this even possible? How?</p>
  
  <h3>EDIT:</h3>
  
  <p>The crux of the matter is obviously accessing the "private" variables <code>width</code> and <code>height</code> of the <code>chart()</code> function by name (represented by the <code>get/setPrivateVar()</code> method calls inside my <code>addProperty</code> idea). Therefore, answers to <a href="https://stackoverflow.com/q/4399794/897968">this related question</a> (which focus on getting a <em>global</em> variable by name) obviously won't work.</p>