title: Javascript classes & event handlers
body: <p>I have a problem with this javascript code:</p>
  
  <pre><code>function MyClass() {
      var id_nr = Math.ceil(Math.random() * 999999);
      this.button_id = 'button_' + id_nr;
  }
  
  
  MyClass.prototype = {
      createButton: function() {
          var msg = 'Button \'' + this.button_id + '\' was clicked';
  
          var my_button = (
              '&lt;input type="button" id="'
              + this.button_id
              + '" value="Click Me" /\&gt;'
          );
  
          document.body.innerHTML += '&lt;div&gt;' + my_button + '&lt;/div&gt;';
          document.getElementById(this.button_id).onclick = function() { alert(msg); }
      }
  };
  
  
  window.onload = function() {
      var s = new MyClass();
      s.createButton();
  };
  </code></pre>
  
  <p>Yes, this current code works fine. But the problem appears when I add more than one MyClass objects:</p>
  
  <pre><code>window.onload = function() {
      var s = new MyClass();
      s.createButton();
  
      var w = new MyClass();
      w.createButton();
  
      /* ...and many other buttons */
  
  };
  </code></pre>
  
  <p>For some reason the <strong><em>onclick</em></strong> event will be triggered only if I click the button that was created last. And I don't know why.</p>
  
  <p>One workaround could be something like this:</p>
  
  <pre><code>&lt;input type="button" onclick="javascript:doSomeThing();" /&gt;
  </code></pre>
  
  <p>But unfortunately this is not the proper solution right row, because my goal is that the onclik event should be able to call another class methods as well. (Those methods are not created yet).</p>
  
  <p>How can I make this code work properly? Any kind of a help is appreciated.</p>