title: Javascript how do I use onclick event on a class method to call another class method?
body: <p>How do I use <code>onclick</code> event on a class method to call another class method?</p>
  
  <p>When I try to do so get this error:</p>
  
  <blockquote>
    <p>Uncaught TypeError: this.method1 is not a function
        at HTMLButtonElement.document.getElementById.onclick (example.html:24)</p>
  </blockquote>
  
  <p>I am suspecting the <code>onclick event</code> accepts only a callback function and not a method.</p>
  
  <p>Is their a workaround?</p>
  
  <p><strong>Here is a sample:</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>class Example {
    constructor(name, age) {
      this.name = name;
      this.age = age;
      this.method2();
    }
    method1(evt) {
      console.log(evt)
      alert("Example Rendered")
    }
  
    method2() {
      document.getElementById("button").onclick = function() {
        this.method1(event);
      }
    }
  
  }
  
  new Example('alexander', '23');</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button id="button"&gt; Click me &lt;/button&gt;</code></pre>
  </div>
  </div>
  </p>