title: Javascript class generating HTML button: how to achieve closure on `this`?
body: <p>Old time OO programmer, new to javascript/html coding.</p>
  
  <p>So I'm playing around with JavaScript "classes", trying to make a reusable unit that writes itself into the html.</p>
  
  <pre><code>&lt;html&gt;
  &lt;script&gt;
  function Foo(min_input, max_input) {
      var n_min_input = min_input;
      var n_input = max_input;
      var curr_shown = min_input;
      this.show_one_more = function () {
          if (curr_shown &lt; n_input) {
              document.getElementById('input' + curr_shown).style = 'display: block';
              curr_shown++;
          }
      }
      this.show_one_less = function () {
          if (curr_shown &gt; n_min_input) {
              curr_shown--;
              document.getElementById('input' + curr_shown).style = 'display: none';
          }
      }
      this.write_inputs = function () {
          for (var i = 0; i &lt; n_min_input; i++) {
              document.write("&lt;input type='text' style='display: block' value='" + i + "' id='input" + i + "' name='input" + i + "'/&gt;");
          }
          for (var i = n_min_input; i &lt; n_input; i++) {
              document.write("&lt;input type='text' style='display: none' value='" + i + "' id='input" + i + "' name='input" + i + "'/&gt;");
          }
          //want to essentially do this, but don't know how
          document.write("&lt;p&gt;&lt;input type='button' onclick='this.show_one_more()' value='+'&gt;&lt;/input&gt;&lt;input type='button' value='-' onclick='this.show_one_less()'/&gt;&lt;/p&gt;");
      }
  }
  var f = new Foo(1, 5);
  f.write_inputs();
  //works here, but would rather it be generated in f.write_inputs();
  document.write("&lt;p&gt;&lt;input type='button' onclick='this.show_one_more()' value='+'&gt;&lt;/input&gt;&lt;input type='button' value='-' onclick='this.show_one_less()'/&gt;&lt;/p&gt;");
  &lt;/script&gt;
  &lt;input type="button" value="stuff" id="sbutton"/&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>So basically, i want to get some sort of closure with this in the document write call on the button. I feel like this is a pattern people may have used in the past (but I could be totally wrong). My ideas:</p>
  
  <p>make a global variable <code>var foo_idx=0</code> and an array <code>var allfoos = [];</code>. In the initialize (body of the class) do <code>this.foo_idx=foo_idx; allfoos[foo_idx]=this;foo_idx++</code> and then I can use <code>allfoos[foo_idx]</code> to capture this. BUT that feels hacky. How do people typically create reusable html elements?</p>